Skip to content

Instantly share code, notes, and snippets.

@chamalis
Last active April 24, 2024 08:28
Show Gist options
  • Save chamalis/f897885eaac199a5e5d927a4e4ec0a5b to your computer and use it in GitHub Desktop.
Save chamalis/f897885eaac199a5e5d927a4e4ec0a5b to your computer and use it in GitHub Desktop.
Compress video files recursively, using x264, placing the output files into the same folder with an appropriate filename (filename_scaled.mp4). First argument is the top-level directory to scan. It avoid overriding already compressed files. Change the filetype (e.g mp4) at the beginning of the script.
#!/bin/bash
FILETYPE=mp4
if [ "$#" -ne 1 ]; then
echo "Usage: <path-to-compress.mp4> target-top-level-directory"
exit
fi
# for all the mp4 except the already scaled ones
find $1 -type f -name "*.$FILETYPE" -not -path "*_scaled*" -exec sh -c '
for file do
dir=$(dirname "${file}")
filename=$(basename -- "${file}")
extension="${filename##*.}"
destfile="${dir}/${filename%.*}_scaled.${extension}"
# -n will prevent overriding the destfile if exists
# The lower the crf value the higher the quality. DVD quality is crf 25
# You can use -threads to limit the number of threads used.
ffmpeg -i "${file}" -vcodec libx264 -acodec copy -crf 27 "${destfile}" -n
done
' sh {} +
# TO DELETE the original files do
# find path -iname "*.mp4" -not -path "*_scaled.mp4" -delete
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment