Rename file by swaping text

2019-08-23 03:53发布

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 ?

3条回答
何必那么认真
2楼-- · 2019-08-23 04:17

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.

查看更多
叼着烟拽天下
3楼-- · 2019-08-23 04:25

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

查看更多
做自己的国王
4楼-- · 2019-08-23 04:34

Using only bash:

for file in *_*.pdf; do
    no_ext=${file%.*}
    new_name=${no_ext##*_}_${no_ext%_*}.${file##*.}
    mv -- "$file" "$new_name"
done
查看更多
登录 后发表回答