0

When I get a file whose name contains the string "x264", I wish to change its extension to ".mp4" (for reasons too detailed to explain here). Examples:

Seinfeld_S02E05_x264.mkv -> Seinfeld_S02E05_x264.mp4

Seinfeld_S02E05_x264.avi -> Seinfeld_S02E05_x264.mp4

What script can I use to automatically make such a change? My computer is a NAS4FREE server running FreeBSD 11.1

UPDATE (after Jeff's response): I forgot to mention that I want this to work in the designated directory and all its sub-directories as well. Perhaps a command rather than a script?

  • Do you know? with this way you are losing your file Seinfeld_S02E05_x264.mkv? In your given sample you are rename two different files name to single name and first one will be deleted completely – αғsнιη Apr 19 '18 at 14:34
  • I was showing the same filename twice just as an example of how I wanted the extension name changed no matter what the original extension name was. I should have given different filenames - sorry for the confusion. – Jim Apr 20 '18 at 2:03
0

Using find:

find -type f -name "*x264*" -execdir sh -c 'echo mv -n "$1" "${1%.*}.mp4"' _ {} \;

The -n option will prevent mv to overwrite to existing files as your given samples files' name renaming to single file name and with this case you are are deleting first file.

To get this work on files without having extensions (suffix):

find -type f -name "*x264*" -execdir sh -c 'file="${1#./}"; 
    echo mv -n "$file" "${file%.*}.mp4"' _ {}  \;

remove echo in above to get rid of dry-run and perform rename on files.

| improve this answer | |
  • Thanks! This did the trick. I was showing the same filename twice just as an example of how I wanted the extension name changed no matter what the original extension name was. I should have given different filenames - sorry for the confusion – Jim Apr 20 '18 at 2:04
2
for f in *x264*.*
do
  mv -- "$f" "${f%.*}".mp4
done

The above runs a shell loop over a "glob" pattern that finds files with "x264" in their filename before some sort of extension (so that there's an extension to rename later); once it has that list of files, it calls mv to do the rename, and uses parameter expansion to strip the extension (period followed by anything *) then manually appends the .mp4 extension.

| improve this answer | |
  • Note that hidden files (files whose name starts with .) are not processed. – Stéphane Chazelas Apr 18 '18 at 12:45
  • Indeed; seems ok for the assumed scenario. dotglob would toggle this behavior, if needed. – Jeff Schaller Apr 18 '18 at 12:47
  • This will also do it for directories having x264 and dot in it's name. – Bhagyesh Dudhediya Apr 19 '18 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.