Sunday, 26 August 2012

How to batch rename files in Linux

Say you have a bunch of pictures and you want to rename them in a certain fashion. You can do it without the use of any external software and without painfully modifying the name of the pictures manually.

You can do it using just one command line! (even without using sed nor rename, if in a bash shell)


Strategy

Open a terminal and access the folder in which you have the files you want to modify:

$ cd ~/Desktop/Folder_name

Then use this command to modify the name of the files inside, to your need:

$ for file in *.* ; do mv [SOURCE_NAME] [DEST_NAME]; done


Examples

The examples below have increasing difficulty. Make sure to understand the previous ones before passing to the more complicated ones. Some knowledge of BASH will certainly help, but even you could use them blindly. Remember to be wise and make backups first, though.

If you have files with the same extension in the folder, such as JPG images, and you want to add a prefix, use this command:

$ for file in *.JPG ; do mv "${file}" "prefix_${file}"; done

If you want to add a suffix, instead, use this:

$ for file in *.JPG ; do mv "${file}" "${file%.JPG}_suffix.JPG"; done

And if your folder is full of mixed files, but you still want to add a suffix:

$ for file in *.*; do mv "${file}" "${file%.*}_suffix.${file#*.}"; done

If you want to number the files as well, sorting for modification time, use:

$ c=0; for file in $(ls -rt); do let c=${c}+1; mv "${file}" "prefix_${c}_suffix.${file#*.}"; done

Have fun renaming!

No comments:

Post a Comment