0

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 ?

Louis D
  • 33
  • 6
  • doesn't look that clumsy to me – Jonathan.Brink Feb 05 '18 at 15:36
  • 1
    [Don't use `ls` for this](https://mywiki.wooledge.org/ParsingLs). You simply mean `for i in *.pdf` and also [fix your quoting](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable). You might want to consult with http://shellcheck.net/ before asking for human assistance. – tripleee Feb 05 '18 at 17:02

3 Answers3

1

One way:

ls *.pdf | awk -F"[_.]" '{print "mv "$0" "$2"_"$1"."$3}' | sh

Using awk, swap the positions and form the mv command and pass it to shell.

Guru
  • 16,456
  • 2
  • 33
  • 46
  • In the general case, this is dangerous. If you have complete confidence that all your file names are trivial, this is fine for private use; but at least the answer should point out the caveats. – tripleee Feb 06 '18 at 05:59
1

Using only bash:

for file in *_*.pdf; do
    no_ext=${file%.*}
    new_name=${no_ext##*_}_${no_ext%_*}.${file##*.}
    mv -- "$file" "$new_name"
done
PesaThe
  • 7,259
  • 1
  • 19
  • 43
1

Using rename you can do the renaming like this:

rename -n 's/([^_]+)_([^.]+).pdf/$2_$1.pdf/g' *.pdf

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

Lars Fischer
  • 9,135
  • 3
  • 26
  • 35