Ubuntu – How to change extension of multiple files recursively from the command line

bashbatch-renamecommand linerename

I have many files with .abc extension and want to change them to .edefg
How to do this from command line ?

I have a root folder with many sub-folders, so the solution should work recursively.

Best Answer

A portable way (which will work on any POSIX compliant system):

find /the/path -depth -name "*.abc" -exec sh -c 'mv "$1" "${1%.abc}.edefg"' _ {} \;

In bash4, you can use globstar to get recursive globs (**):

shopt -s globstar
for file in /the/path/**/*.abc; do
  mv "$file" "${file%.abc}.edefg"
done

The (perl) rename command in Ubuntu can rename files using perl regular expression syntax, which you can combine with globstar or find:

# Using globstar
shopt -s globstar
files=(/the/path/**/*.abc)  

# Best to process the files in chunks to avoid exceeding the maximum argument 
# length. 100 at a time is probably good enough. 
# See http://mywiki.wooledge.org/BashFAQ/095
for ((i = 0; i < ${#files[@]}; i += 100)); do
  rename 's/\.abc$/.edefg/' "${files[@]:i:100}"
done

# Using find:
find /the/path -depth -name "*.abc" -exec rename 's/\.abc$/.edefg/' {} +

Also see http://mywiki.wooledge.org/BashFAQ/030

Related Question