Search code examples
linuxfilerenamebulk

Rename files that have consecutive numbers for extensions


I have a directory with a few hundred files in the following format:

file.txt.1
file.txt.2
file.txt.3
file.txt.4
...

I need to rename these all to this format:

file1.txt
file2.txt
file3.txt
file4.txt
...

Solution

  • Not sure if this is the best way to do what you're asking but it will rename all the files the way you need. Just save it to a file (rename.sh for example) then give it execution permissions (chmod +x rename.sh) and run with ./rename.sh

    #!/bin/bash
    for filename in file*; do 
        newFile=`echo $(basename $filename) | awk -F'.' '{print $1 $3 "." $2}'`
        echo mv \"$filename\" \"$(dirname $filename)/$newFile\";
    done | /bin/bash
    

    If you wanted to run a dry-run, replace | /bin/bash with > renames.txt. This will save all the renamed files to the text file where you can review the changes.