Regex rename a filename using rename linux command

Viewed 104

I am trying to rename a file first_second.pdf into first_0second.pdf

So, I read about capturing and back reference. But somehow it doesnt work. Can anyone tell me what I am doing wrong?

rename 's/\(.*_\)\([1-9]\).pdf$/$10$2.pdf/' first_1.pdf

I am expecting first_1.pdf to renamed to first_01.pdf

2 Answers

The -n argument shows you what it is going to do without actually doing it which is good for testing. Match and capture the first part up to and including the underscore. Then match and capture 1 or more numbers followed by the literal dot and anything else until the end of the line. Replace with the first captured group (braces around the group number in order to separate it from the literal '0'), a literal '0', then the 2 remaining captured groups.

rename -n 's/(.*_)([0-9]+)(\..*)$/${1}0$2$3/' first_1.pdf

rename(first_1.pdf, first_01.pdf)

The problem was the escape character and the curly brackets surrouding the back references. This is because rename internally uses posix-extended. Escape character would have been necessary, if rename had used posix-basic as regextype.

By removing the escapes and adding curly brackets for the back references, the regex expression worked.

rename 's/(.*_)([1-9]).pdf$/${1}0${2}.pdf/' first_1.pdf
Related