Notes

Batch renaming files in Bash

Edit on GitHub

Bash Scripting
2 minutes

Use rename, which is a Perl script and maybe on your system already. You can use the rename command to quickly rename files using a regular expression pattern. For instance, if you wanted to rename all files containing foo to contain bar instead, you could use a command like this one:

1rename –v 's/foo/bar/g' *    

How to rename multiple files based on a pattern

1for f in * ; do cp "$f" 2014-08-26-"$f" ; done    
1mv $f ${f#[0-9]*-}

Test

1$ ls
223-a  aa23-a  hello
3$ for f in *; do mv $f ${f#[0-9]*-}; done
4$ ls
5a  aa23-a  hello

Batch rename files based on file type, remove space

Let’s say you have image files named like this:

  • a88d09 989_01.jpg
  • a88d09 989_03.jpg
  • a88d09 989_05.jpg
  • a88d09 989_07.jpg

The following will rename all these .jpg files and remove the space in file name.

1IFS="\n"
2for file in *.jpg;
3do
4    mv "$file" "${file//[[:space:]]}"
5done    

Change spaces into Underscores

1rename "s/ /_/g" *    

OR, if you don’t have rename

1for f in *\ *; do mv "$f" "${f// /_}"; done

Rename only files to change spaces into Underscores

1find -name "* *" -type f | rename 's/ /_/g'

Rename only dirs to change spaces into Underscores

1find -name "* *" -type d | rename 's/ /_/g'

Change spaces into underscores, recursively

1find /tmp/ -depth -name "* *" -execdir rename 's/ /_/g' "{}" \;

/tmp/ is the folder where you are looking for files,