====== BASH - Files - Rename multiple files ======
The **rename** command which is part of the Perl installation helps.
All you need to know is the basics of regular expressions to define how the renaming should happen.
----
To add a '.old' to every file in your current directory. At the end of each expression ($) a '.old' will be set:
rename 's/$/.old' *
----
To make the filenames lowercase:
rename 'tr/A-Z/a-z/' *
----
To remove all double characters:
rename 'tr/a-zA-Z//s' *
----
You have many JPEG files that look like “img0000154.jpg” but you want the first five zeros removed as you don’t need them:
rename 's/img00000/img/' *.jpg
**NOTE:** Any Perl operator can be used as an argument.
The actual documentation for the 's' and 'y'/'tr' operators are found in the 'perlop' manpage.
----
===== Add an extension =====
ls
file1 file2 file3
Add the extension ".txt"
for F in $(ls);do mv $F $F.txt;done
Check the result:
ls
file1.rm file2.rm file3.rm
----
===== Change the extension =====
Change the extension from ".txt" to ".mp3":
for F in $(ls);do mv $F $(echo $F|sed -e 's,\.rm,,').mp3 ;done
Check the result:
ls
file1.mp3 file2.mp3 file3.mp3
----
===== Remove the extension =====
for F in $(ls);do mv $F $(echo $F|sed -e 's,\.mp3,,') ;done
Check the result:
ls
file1 file2 file3
----
===== Only use ASCII characters =====
find . -type f -exec bash -c 'for f do d=${f%/*} b=${f##*/} nb=${b//[^A-Za-z0-9._-]/_}; [[ $b = "$nb" ]] || mv "$f" "$d/$nb"; done' _ {} +
**NOTE:** To test, use
find . -type d -exec bash -c 'for f do d=${f%/*} b=${f##*/} nb=${b//[^A-Za-z0-9._-]/_}; [[ $b = "$nb" ]] || echo mv "$f" "$d/$nb"; done' _ {} +
* NOTE the **echo** statement included, which just prints out the command that will be run.
* To actually do the move action, just remove the **echo** part.
**NOTE:** For directories use
find . -type d -exec bash -c 'for f do d=${f%/*} b=${f##*/} nb=${b//[^A-Za-z0-9._-]/_}; [[ $b = "$nb" ]] || mv "$f" "$d/$nb"; done' _ {} +