Linux Tips 10: Rename multiple files

|
Renaming multiple files in Linux is surprisingly difficult given the simplistic power provided by many other system commands. Unlike DOS, which provided a rename command that allowed wild cards, Linux's rename/mv command is less versatile. Therefore to rename files one needs to write a loop. Luckily bash helps a lot here.

Lets say we have in our directory a number of .txt files that we need to rename to .nfo. To do this we would need to use the command:

for f in *.txt; do mv "${f}" "${f/.txt/.nfo}"; done;
It is quite a long command, but it basically executes a loop and tells it to take each f file name in *.txt and give it a name where a match for .txt is replaced with .nfo. While I have not tried more complex patterns it should be possible to use any regular expression. Please note that the above code only does one replacement. If multiple is needed then two slashes are required after f, ie. {$f//.txt/.nfo}

0 comments:

Post a Comment