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, ...

1

1 Answer 1

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
6
  • The s in s/// is necessary? Commented Jun 10, 2016 at 1: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/' *. Commented Jun 10, 2016 at 1: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. Commented Jun 10, 2016 at 4: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. Commented Jun 10, 2016 at 4:33
  • 1
    yeah, i have that sed habit too. Commented Jun 10, 2016 at 4:38

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.