4

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?

5

Using rename

A generally useful tool for this type of activity is rename from the perl package. It applies a perl substitution to the file name:

rename 's/file/file0/' file[0-9][0-9].ext

How this works:

  • s/file/file0/

    This is a perl substitution command. It replaces the occurrence of file in a file name with file0.

  • 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 of rename. There is also a rename utility that is part of util-linux but it works differently.

Using bash

This approach uses a for loop combined with pattern substitution:

for f in file[0-9][0-9].ext; do mv "$f" "${f/file/file0}"; done

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 under bash. Thus, this should work on the usual command line.

  • Thank you for the reply. I will look more into regular expressions as well. – user300704 Dec 15 '14 at 7:49
1

This rename with using different regex:

rename -n 's/[^0-9](([0-9]){2})\.ext$/0$1.ext/' *

[^0-9](([0-9]){2})\.ext$ Matches any non-digit[^0-9] followed by group of numbers with length=2 which is ends with .ext. So in replacement part, add a 0 and prints group of matched $1 and then their extension.

Or alternative for regex:

rename -n 's/[^\d](\d{2})\.ext$/0$1.ext/' *

\d matches a number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.