1

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

Renamed:

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
  • 5,864
  • 2
  • 28
  • 31
Juicee
  • 31
  • 4

2 Answers2

2

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

cms
  • 5,864
  • 2
  • 28
  • 31
0

you can use cut -d"-" -f3:

for VAR in *-*-*.txt; do mv "$VAR" "`echo $VAR | cut -d'-' -f3 `"; done

or, to ignore the first space:

for VAR in *-*-*.txt; do mv "$VAR" "`echo $VAR | sed -e 's/^.*- //g'`"; done
kittykittybangbang
  • 2,380
  • 4
  • 16
  • 27
Ali ISSA
  • 398
  • 2
  • 10