Replace and add leading zeros when renaming files

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

I have a bunch of files, some with a simple and clean name (for example, 1E01.txt), and some with a lot of extra features:

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

etc. The number after the โ€œSampleโ€ and the letter + the number after the โ€œNameโ€ are important here - the rest is one-time. If I get rid of the important parts, the file name comes down to the same pattern as the "clean" file names (2E01.txt, 2E02.txt, ..., 12E01.txt). I managed to rename the files with the following expression (I invented it myself, I donโ€™t know if it is very elegant, but it works fine):

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

Now the second part adds a leading zero for single-digit file names, for example, 1E01.txt turns into 01E01.txt. I managed to do this (found and changed it to 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 combine both expressions in only one rename command? I know I can make a bash script to automate the process, but I want to find a one-pass renaming solution.

thanks

+4
source share
2 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 team a bit to suit your needs.

+10
source

Well, if this is your regular expression "parsing", you limit the files that the script can act on those that match this pattern. So, sprintf using the same literals is not a more specialized case, and you could just do this:

 s{Sample(\d+)_Name_(\p{IsUpper})(\d+)} {sprintf "Sample%02d_Name_%s%03d", $1, $2, $3}e ; 

Here you again use the same well-known functions and simply format the accompanying numbers.

  • /e switch for "eval" and evaluates the replacement as Perl for each match.
  • I renamed some of your expressions to more standard character character characters: [AZ] becomes the property class \p{IsUpper} , [0-9] becomes the numeric code \d (it is also possible \p{IsDigit} ).
+1
source

Source: https://habr.com/ru/post/1444339/


All Articles