Search code examples
linuxrenamemv

Rename file while keeping the extension in Linux?


I have a directory that contains multiple files with different extensions (pdf, doc, txt...etc).

I'm trying to rename all files according to the directory name while keeping the file extension the same. The code below works fine if all files are PDF otherwise it will change txt file extension to pdf too.

How can I rename files while preserving the file extension

mv "$file" "${dir}/${dir}-${count}.pdf"

Solution

  • you can do this through bash.

    can you please provide more details. how your deciding this $dir and $count variable value.

    if you already know by what you want to change the file name like below

    OLD NAME|NEW NAME|Path

    test.1|newtest.1|Path

    arty.2|xyz.2|Path

    if you want to replace it by specific names then you can prepare a list like above and then traverse through the file by while or for loop. below is simple bash snippet for case where you have files under multiple directory

    while IFS="|" read OLD NEW PATH
    do
        cd $Path
    
        filename=`echo $NEW|awk -F '.' '{print $1}'`
    
        filetype=`echo $NEW|awk -F '.' '{print $2}'`
    
        mv $OLD $filename.$filetype
    
    done<FILE_PATH
    

    if want to perform operation under single directory then below snippet will work.

    for i in $(ls /tmp/temp)
    do 
        filename=`echo $i|awk -F "." '{print $1}'`
        fileType=`echo $i|awk -F "." '{print $2}'`
        mv $i $filename.$fileType
    done