Bulk Rename Multiple Files

I wrote this post as a memo, in case I cannot remember those commands…

In Linux/Unix, depending on the situation, we can rename a massive of files in bulk.

There are two versions of rename. The C version is shipped with util-linux package. It has only limited features, and it does not support regular expressions. However, there is also a Perl version with more power.

In following examples, I will not distinguish C and Perl version rename. Just try it.

Example 1: there is a batch of .jpg files, theirs names are starting with ‘photo’. Now I need to replace ‘photo’ with ‘pic’.

1
$ rename photo pic photo*.jpg

Example 2: I need to replace all .jpg extensions with .jpeg.

1
$ rename .jpg .jpeg *.jpg

Or

1
$ rename 's/\.jpg$/\.jpeg/' *.jpg

Example 3: there is a batch of .bak files, and I need to remove all .bak extensions.

1
$ rename 's/\.bak$//' *.bak

Example 4: change all upper case letters within file names into lower case letters.

1
$ rename 'y/A-Z/a-z/' *

Vice vesa, if you need to change all lower case letters to upper case letters:

1
$ rename 'y/a-z/A-Z/' *

Example 5: remove spaces within all file names.

1
$ rename 's/[ ]+/_/g' *

You can replace the space between brackets with [:space:], i.e.

1
$ rename 's/[[:space:]]+/_/g' *

Example 6: append ‘photo’ as file name prefix.

1
$ rename 's/^/photo/' *

Example 7: append .zip as file name suffix.

1
$ rename 's/$/.zip/' *

Example 8: rename all files in order. For example, rename 1.jpg, 2.jpg, 3.jpg…100.jpg to 001.jpg, 002.jpg, 003.jpg…100.jpg.

1
2
3
4
$ rename 's/^/00/' [0-9].jpg
# 1.jpg...9.jpg will be renamed as 001.jpg...009.jpg in this step
$ rename 's/^/0/' [0-9][0-9].jpg
# 10.jpg...99.jpg will be renamed as 010.jpg...090.jpg in this step

Here are some examples of renaming through scripts, to implement more complicated needs.

Example 9: rename abcd.jpg as abcd_efg.jpg.

1
$ for var in *.jpg; do mv "$var" "${var%.jpg}_efg.jpg"; done

Example 10: rename abcd_efg.jpg as abcd_lmn.jpg.

1
$ for var in *.jpg; do mv "$var" "${var%_efg.jpg}_lmn.jpg"; done

Example 11: change _?.jpg files to _0?.jpg.

1
$ for var in `ls *_?.jpg`; do mv "$var" `echo "$var" |awk -F '_' '{print $1 "_0" $2}'`; done

Example 12: change first three letters of the file names to ‘abcde’.

1
$ for var in `ls`; do mv -f "$var" `echo "$var" |sed 's/^.../abcde/'`; done

Example 13: change last four letters of the file names to ‘uvwxyz’.

1
$ for var in `ls`; do mv -f "$var" `echo "$var" |sed 's/....$/uvwxyz/'`; done

Examples 14: change .txt extensions to .txt_bak extensions.

1
$ ls *.txt|xargs -n1 -i{} mv {} {}_bak

That’s all. I think these examples could cover most of the common situations.