Ahmad
Ahmad

Reputation: 9658

How can I replace numbers in filenames with leading zero in bash?

There are similar questions about how to add numbers with leading zero etc. but in my case my filename has two numbers which is the number of chapter and the number of page. Both lack the leading zero, so they aren't sorted alphabetically. Using rename or any other method I want to convert files like these:

file_1_1.mp3  to file_01_01.mp3
file_1_12.mp3 to file_01_12.mp3
file_12_1.mp3 to file_12_01.mp3
...

I tried this:

rename 's/\d+/sprintf("%02d",$&)/e' *.mp3

but it just add leading zero to the chapter number.

Upvotes: 2

Views: 649

Answers (2)

Bill Jetzer
Bill Jetzer

Reputation: 1115

This shell script works:

for file in *mp3
do
    new=$(echo "$file" | sed 's/_/_0/g; s/_0\([0-9][0-9]\)/_\1/g;');
    mv "$file" "$new";
done;
  • Appends a 0 to each underscore found
  • Removes that 0 if it resulted in at least digits in a row

Edit: added global flag to the 2nd substitute command, per comment by @PaulHodges

Upvotes: 1

Gilles Quénot
Gilles Quénot

Reputation: 185025

Like this:

rename -n 's/(\d+)_(\d+)\./sprintf("%02d_%02d.", $1, $2)/e' *.mp3

Remove -n switch when the output looks good for you

Output

rename(file_1_12.mp3, file_01_12.mp3)
rename(file_1_1.mp3,  file_01_01.mp3)
rename(file_12_1.mp3, file_12_01.mp3)

man rename

warning There are other tools with the same name which may or may not be able to do this, so be careful.

The rename command that is part of the util-linux package, won't.

If you run the following command (GNU)

$ rename

and you see perlexpr, then this seems to be the right tool.

If not, to make it the default (usually already the case) on Debian and derivative like Ubuntu :

$ sudo apt install rename
$ sudo update-alternatives --set rename /usr/bin/file-rename

For archlinux:

pacman -S perl-rename

For RedHat-family distros:

yum install prename

The 'prename' package is in the EPEL repository.


For Gentoo:

emerge dev-perl/rename

For *BSD:

pkg install gprename

or p5-File-Rename


For Mac users:

brew install rename

If you don't have this command with another distro, search your package manager to install it or do it manually (no deps...)


This tool was originally written by Larry Wall, the Perl's dad.

Upvotes: 3

Related Questions