Michel Kapelle
Michel Kapelle

Reputation: 149

Shell script to adjust filenames (from the end)

I am running into a problem as how to do a BATCH adjustment for changing filenames.

All my files look like this:

1602017EN.MPG 1802312EN.MPG etc.

I need to change 2 thing for all filenames.

I need to adjust the file extension to lowercase, so it reads .mpg instead of .MPG. For this part, i am using an apple automator service. This works perfectly.

Second, i need to remove the last 2 characters, the letters.

So the first item would read 1602017.mpg and so on.

It would be perfect if it can be done with a shell script that i can add to my automator service, so it makes change no1 and no2 after each other.

Thank you VERY much in advance!

Upvotes: 1

Views: 55

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753535

Assuming you are using bash for shell scripting, you could do it easily using sed:

for file in "$@"
do
    name=$(echo "$file" | sed 's/[A-Z][A-Z].MPG$/.mpg/')
    mv "$file" "$name"
done

(working on the reasonable looking assumption that there are no newlines in the file names).

However, you can also do it directly in bash without invoking an external program:

$ for file in 1602017EN.MPG 1802312EN.MPG; do echo ${file/[A-Z][A-Z].MPG/.mpg}; done
1602017.mpg
1802312.mpg
$

Upvotes: 1

Related Questions