I have a situation where I have the following:
file01.ext
.
.
.
file99.ext
file100.ext
.
.
.
And I want to (using rename ) insert the '0' for the files 01-99 (so that they become 000-099) but not modify files larger than 100. Which expression should I use and what is a good source on learning regular expressions such as these?
On Windows I would have used Total Commander's multi rename function which has a very simple renaming syntax. Are there some good alternatives for that tool (multi-rename) for Ubuntu?
Best Answer
Using
rename
A generally useful tool for this type of activity is
rename
from theperl
package. It applies a perl substitution to the file name:How this works:
s/file/file0/
This is a
perl
substitution command. It replaces the occurrence offile
in a file name withfile0
.file[0-9][0-9].ext
This is the list of files that
rename
is to operate on.[0-9]
means any number from 0 to 9.[0-9][0-9]
means any two numbers, one following the other.The manpage for
rename
is here.Note: This requires the
perl
version ofrename
. There is also arename
utility that is part ofutil-linux
but it works differently.Using
bash
This approach uses a
for
loop combined with pattern substitution:How it works:
for f in file[0-9][0-9].ext; do
This starts a loop over each file name that matches the glob
file[0-9][0-9].ext
.mv "$f" "${f/file/file0}"
This renames the files using the bash's pattern substitution. It replaces
file
with file0` in the file name.done
This marks the end of the
for
loop.This approach requires
bash
(or other advanced shell).bash
is the default interactive shell and this approach will work underbash
. Thus, this should work on the usual command line.