bash
07/01/2022

Renaming multiple files in Linux & OSX in one line

By snorlaxprime

Renaming multiple files with the mv command is easier if you know a little bit of Bash scripting. I stumble across the following when I try to rename a bunch of file extension.

  • The following command will add a .txt file extension to all files in your present working directory.
$ for i in $( ls ); do mv $i $i.txt; done
  • To remove a file extension from all files, you can use this command.
$ for i in $( ls *.txt ); do mv $i ${i%.*}; done
  • We can also change the file extension of every file. The following command will change all files with the .log extension to .txt.
$ for i in *.log; do mv -- "$i" "${i%.log}.txt"; done
  • You can also use the find command, along with -exec option or xargs command to rename multiple files at once. This command will append .bak to every file that begins with the pattern “file”.
$ find . -type f -name 'file*' -print0 | xargs --null -I{} mv {} {}.bak
  • This command uses find and the -exec option to append “_backup” to all files that end in the .txt extension.
$ find . -name "*.txt" -exec mv {} {}_backup \;
  • We can also use xargs to do the same thing. This command will accept standard input from the ls command, then use xargs to append “_backup” to all files that end in the .txt extension.
$ ls *.txt | xargs -I{} mv {} {}_backup
  • To change all files with the .txt in the present directory to have lowercase letters only, this command will do the job.
$ for i in `ls *.txt`; do mv "$i" "`echo $i | tr '[A-Z]' '[a-z]'`"; done

All the above command is performed with native mv command, so we don’t need to download any additional software and it will work in all the linux variant. I hope you find it useful.