1

I have files like ABC_asd_f.txt, DEF_qwe_r.txt, ...

How can I exchange the uppercases before the first underscore with the lowercases after? So ABC_asd_f.txt becomes asd_f_ABC.txt, DEF_qwe_r.txt becomes qwe_r_DEF.txt, ...

wsdzbm
  • 2,836

1 Answers1

4

Use perl rename. Firstly use the -n flag for a dry-run.

rename -n 's/^(...)_(..._.)/$2_$1/' *

Then, if you are happy, run it for real.

rename 's/^(...)_(..._.)/$2_$1/' *

Explanation

This uses capturing groups.

  • rename 's/foo/bar/' *: replace foo with bar for all files *.
  • ^(...)_(..._.): from the beginning of the line ^, capture the first three characters (...), skip over _, then capture the next five characters, where the fourth is underscore (..._.).
  • $2_$1: replace the string above with the capturing groups reversed (i.e. the second, an underscore, then the first).

Rename version

There are two renames in Linux-land. You can tell if it's perl rename with the following

$ rename --version
perl-rename 1.9

The other one will give a different result.

$ rename --version
rename from util-linux 2.28
Sparhawk
  • 19,941
  • The s in s/// is necessary? – wsdzbm Jun 10 '16 at 01:08
  • 1
    @Lee The s indicates that the perl expression should use replacement. More information here. You can actually use other perl expressions here, e.g. try prename -n 'y/a-z/A-Z/' *. – Sparhawk Jun 10 '16 at 01:20
  • 1
    +1. For perl capture groups, \1, \2 will work in most cases but $1, $2 is more correct. or even ${1}, ${2}. see man perlre and search for Warning on \1. – cas Jun 10 '16 at 04:33
  • BTW, a little-known fact about perl rename: you can use ANY perl statement(s) with it (not just s/// or y// etc) even very complex perl scripts - if they change $_, the current file being processed will be renamed to $_. Otherwise it won't be renamed. – cas Jun 10 '16 at 04:33
  • Thanks for that @cas. I think I've hit warnings about that before, and have never really chased it up. That was a good reference. Cheers. (I've edited the answer accordingly.) – Sparhawk Jun 10 '16 at 04:36
  • 1
    yeah, i have that sed habit too. – cas Jun 10 '16 at 04:38