Home > Mobile >  Batch rename in unix: swap digits_*.* into *_digits.*
Batch rename in unix: swap digits_*.* into *_digits.*

Time:05-26

I need to batch rename a list of files if the name matches a specific pattern, the pattern starts with 1 or more digit, followed by underscore, then alphanumeric. For example: "123_ABC123.txt" (the extension can be anything, doesn't have to be 'txt').

I figured the regex would look like this:

\d _*.*

But I'm not sure how I can implement this in Unix, specifically, how do I express that the first part (\d ) should swap with the second part (*) with underscore in between?

Thanks!

CodePudding user response:

You may use this rename command:

rename -n 's/^(\d )_(. )(\.[^.] )$/$2_$1$3/' [0-9]*.*

123_ABC123.txt' would be renamed to 'ABC123_123.txt'

Once satisfied you can remove -n (dry run) option.

Explanation:

  • ^(\d ): Match 1 digits at the start in capture group #1
  • _: Match a _
  • (. ): Match 1 of any characters in capture group #2
  • (\.[^.] )$: Match dot and extension to capture in group #3 before line end
  • $2_$1$3: Insert _ between capture group 2 and 1 and preserve extension in $3
  • Related