Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace and add leading zeros when renaming files

Please be patient, this post will be somewhat long...

I have a bunch of files, some of them with a simple and clean name (e.g. 1E01.txt) and some with a lot of extras:

Sample2_Name_E01_-co_032.txt
Sample2_Name_E02_-co_035.txt
...
Sample12_Name_E01_-co_061.txt

and so on. What is important here is the number after "Sample" and the letter+number after "Name" - the rest is disposable. If i get rid of the non-important parts, the filename reduces to the same pattern as the "clean" filenames (2E01.txt, 2E02.txt, ..., 12E01.txt). I've managed to rename the files with the following expression (came up with this one myself, don't know if is very elegant but works fine):

rename -v 's/Sample([0-9]+)_Name_([A-Z][0-9]+).*/$1$2\.txt/' *.txt

Now, the second part, is adding a leading zero for filenames with just one digit, such as 1E01.txt turns into 01E01.txt. I've managed to to this with (found and modified this on another StackExchange post):

rename -v 'unless (/^[0-9]{2}.*\.txt/) {s/^([0-9]{1}.*\.txt)$/0$1/;s/0*([0-9]{2}\..*)/$1/}' *.txt

So I finally got to my question: is there a way to merge both expressions in just one rename command? I know I could do a bash script to automate the process, but what I want is to find a one-pass renaming solution.

thanks

like image 922
h.mon Avatar asked Dec 15 '22 17:12

h.mon


1 Answers

You can try this command to rename 1-file.txt to 0001-file.txt

# fill zeros
$ rename 's/\d+/sprintf("%04d",$&)/e' *.txt

You can change the command a little to meet your need.

like image 130
kev Avatar answered Jan 05 '23 13:01

kev