I need to rename files by swaping some text. I had for example :
CATEGORIE_2017.pdf
CLASSEMENT_2016.pdf
CATEGORIE_2018.pdf
PROPRETE_2015.pdf
...
and I want them
2017_CATEGORIE.pdf
2016_CLASSEMENT.pdf
2018_CATEGORIE.pdf
2015_PROPRETE.pdf
I came up with this bash version :
ls *.pdf | while read i
do
new_name=$(echo $i |sed -e 's/\(.*\)_\(.*\)\.pdf/\2_\1\.pdf/')
mv $i $new_name
echo "---"
done
It is efficient but seems quite clumsy to me. Does anyone have a smarter solution, for example with rename ?
One way:
Using awk, swap the positions and form the mv command and pass it to shell.
Using
rename
you can do the renaming like this:The option
-n
does nothing, it just prints what would happen. If you are satisfied, remove the-n
option.I use
[^_]+
and[^.]+
to capture the part of the filename before and after the the_
. The syntax[^_]
means everything but a_
.Using only
bash
: