Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am trying to use a regex to rename few files following this post

Renaming files using regular expressions - Linux

There are my files -

abcd_some_random_alphanumeric_1.pdf
abcd_some_random_alphanumeric_2.pdf
abcd_some_random_alphanumeric_3.pdf
abcd_some_random_alphanumeric_4.pdf
abcd_some_random_alphanumeric_5.pdf

I would like to rename the files to

abcd_1.pdf
abcd_2.pdf 
abcd_3.pdf 
abcd_4.pdf 
abcd_5.pdf 

I am trying the following

rename 's/abcd_.*_(/d+).pdf/abcd_${1}.pdf/' *.pdf

But I get lots of errors -

Unknown regexp modifier "/a" at (user-supplied code), near ""
Unknown regexp modifier "/b" at (user-supplied code), near "{
#line 1
Unknown regexp modifier "/c" at (user-supplied code), near "{
#line 1
...........

However, I want the _1, _2, _3 etc in the end.. and I dont know how to capture data using a regular expression from the original string and put the captured group in the replace part.

There's a warning there, in bold letters: "There are other tools with the same name which may or may not be able to do this, so be careful." Indeed, man7.org/linux/man-pages/man1/rename.1.html shows a completely different utility. Check the manpage/help text for yours. – ivan_pozdeev Jun 2, 2018 at 8:19

Your syntax is off, and a single digit in regex is \d, with a backslash not forward slash. Also the dot in the extension .pdf should be escaped. Try this:

rename 's/abcd_.*_(\d+)\.pdf/abcd_$1.pdf/' *.pdf
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.