Pattern based, batch file rename in terminal
The solution to the above example, using rename:
rename -v -n 's/file_\d{1,3}/upl/' file_*.png
Usage:
rename [options] [Perl regex search/replace expression] [files]
From man rename
:
-v, --verbose
Verbose: print names of files successfully renamed.
-n, --no-act
No Action: show what files would have been renamed.
rename MAY take regex as the arguments.
What we are looking at is the content between the single quotes '
. You can place regex separated by /
.
Formula: s/(1)/(2)/
where (1)
= search pattern, and (2)
= replace pattern.
So, familiarize youself with regex, and enjoy pattern based batch file renaming!
This can be done with little magic of bash parameter expansion!
for f in file_[0-9]*_*; do mv $f upl_${f#file_[0-9]*_}; done
file_[0-9]*_*;
- First pattern is used to go trough all files that begin with 'file_anynumber_'
${f#file_[0-9]*_}
- The second pattern file_[0-9]*_
is used in parameter expansion which tells bash to remove 'file_anynumber_' from the begging of the string.
For more information on Parameter expansion
:
man bash
if files are in severals directories, use rename after a find like :
find -iname file_*.png -type f -exec rename -n 's/file_[0-9]{3}(.*\.png)/upl$1/' {} \;
the -n after rename is to test, remove it to proceed !-)
like this, you associate find and rename power.
Personally, I used it to rename sources header .h to .hpp
find -iname *.h -type f -exec rename 's/(.*\.)h/$1hpp/' {} \;