Habib Inman Habib Inman - 2 years ago 62
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...

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

Answer Source

You have a typo in your variable expansion:


should have been:


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download