Move numbers in a filename to the start

0

1

I have several files in a folder, with names in the form: SOMETEXT1 number SOMETEXT2.mp3, or SOMETEXT number.mp3. I want to rename these to number SOMETEXT SOMETEXT2.mp3, or number SOMETEXT.mp3. Using bash and common GNU command line tools, how would I achieve this?

w4etwetewtwet

Posted 2013-11-02T12:41:26.237

Reputation: 272

2Could you provide an actual example file name for each variant you have? – Daniel Beck – 2013-11-02T12:57:13.903

Answers

1

Using perl-rename (sometimes called prename):

prename -v 's/^(.+) (\d+)( .+|\.[^.]+)$/\2 \1\3/' *

Use -n to just test without renaming.

The same with bash:

re='^(.+) ([0-9]+)( .+|\.[^.]+)$'
for file in *; do
    new=$file
    if [[ "$file" =~ $re ]]; then
        new="${BASH_REMATCH[2]} ${BASH_REMATCH[1]}${BASH_REMATCH[3]}"
    fi
    if [[ "$new" != "$file" ]]; then
        mv -v "$file" "$new"
    fi
done

user1686

Posted 2013-11-02T12:41:26.237

Reputation: 283 655

That works for the first variety of names, (text number text.mp3), but not the second (text number.mp3), How would I solve this? Thank you very much for your help. – w4etwetewtwet – 2013-11-02T13:14:47.293

Ah, I forgot the extension. Fixed. – user1686 – 2013-11-02T13:20:36.023

Working perfectly, thankyou very much. – w4etwetewtwet – 2013-11-02T13:33:54.563