2

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

need a g modifier on the second s/// also to make sure it gets them all across the name, yes?
@PaulHodges: Good catch. Not an issue with the three files given in the question, but would be if the file contains multiple 2-digit sequences at the start, e.g., file_12_12.mp3.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.