Home > other >  Why doesn't the Perl regex `[1-22]` work for the rename command in linux? [duplicate]
Why doesn't the Perl regex `[1-22]` work for the rename command in linux? [duplicate]

Time:10-04

I had a bunch of files labelled like: text.s01e01.text.mkv

There are 22 files so I needed to quickly rename them to just 1.mkv, 2.mkv, etc. What I had to do was:

rename 's/text.S01E(0[1-9]).text/$1.mkv'/g *mkv

rename 's/text.S01E(1[0-9]).text/$1.mkv'/g *mkv

rename 's/text.S01E(2[0-2]).text/$1.mkv'/g *mkv

I tried doing S01E(0[1-22]) but that didn't work.

Can someone just help me understand why the Perl regular expression didn't work?

CodePudding user response:

You can use a single rename command instead of three :

rename 's/text\.s01e0?(\d )\.text/$1/' *.mkv

To test perl regex substitution :

perl -ne 's/text\.s01e0?(\d )\.text/$1/; print' <<< "text.s01e10.text.mkv"
# output : 10.mkv

CodePudding user response:

Assuming your rename supports Perl regular expression syntax, the problem with [1-22] is that the 22 does not work the way you expect it to work. The square brackets define Bracketed Character Classes. Single digits work as expected: [1-2] defines a range of characters between 1 and 2 (inclusive). [1-2] matches a 1 or a 2.

However, [1-22] is interpreted as the range 1-2 and the character 2. It matches 1 or 2 or 2 -- effectively just 1 or 2.

If you can tolerate matching all 2-digit sequences from 00 to 99, you could use:

([0-9]{2})

  • Related