Juicee Juicee - 2 years ago 146
Bash Question

How to remove a common prefix pattern from multiple file names in bash

I would need to rename thousands of files, right now I'm doing it with removing first x characters, but it can be a lengthy process since the number of chars needed to be removed changes.

Source files are named like this:

4023 - 23 - Animal, crocodile 4 legs.txt
243 - 4 - Animal, dog 4 legs.txt
5450 - 2 - Animal, bird 2 legs.txt


Animal, crocodile 4 legs.txt
Animal, dog 4 legs.txt
Animal, bird 2 legs.txt

It seems the easiest it would be to trim everything before "A" appears, but I do not know how to do this. Something with a loop that could be used as a bash script would be awesome.

cms cms
Answer Source

You can use bash parameter expansion

${VAR#*-*- }

to remove a prefix by pattern. That's using the text in the shell variable VAR and generating a string based on removing a prefix that matches the wildcard pattern *-*- - e.g. any characters then a dash then any characters and then a second dash and a space

In order to get the filenames in a loop you can just use a bash for with a pattern

for VAR in *.txt; do mv "$VAR" "${VAR#*-*- }"; done

the quoting is necessary in the mv to prevent the whitespace in the filenames being split up into multiple arguments by the shell

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download