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
, ...
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
, ...
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/' *
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).There are two rename
s 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
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
, \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
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
rename
; also seeman rename
. – Wildcard Jun 10 '16 at 01:20