Habib Inman Habib Inman - 6 months ago 11
Bash Question

Renaming Files Through Script

I have a few files that are incorrectly named (with the extension added twice to the end). I was trying to write a bash script that would scan the directory and rename them, but it throws an error of:


cannot move ‘/var/random/file/file1.avi.mp4’ to ‘{/var/random/file/file1.avi.mp4%.avi.mp4}.mp4’: No such file or directory


I just want to properly rename the file extension, and am not sure where the error comes into play. For example, the error above, should have a file extension of .mp4. Below is my script, if someone could assist, I would be in debted...

#/bin/sh
for file in $(find /var/random/ -type f -name "*.avi.mp4"); do
mv "$file" "{$file%.avi.mp4}.mp4"
done

Answer

You have a typo in your variable expansion:

"{$file%.avi.mp4}.mp4"

should have been:

"${file%.avi.mp4}.mp4"

However you might want to take a look at rename (perl-rename)

perl-rename 's/[^.]+\.(?=[^.]+$)//' /var/random/*/*.avi.mp4

The regex will remove the second to last extension in file names:

/path/to/file/foo.bar.baz -> /path/to/file/foo.baz