222 words
1 minutes
Snippet: Batch Compression Commands for Images, Videos, and PDFs

Snippet: Batch Compression Commands for Images, Videos, and PDFs#

NOTE

Back up your files before running any of these commands because the image and video commands delete the original files after compressing them.

Compress images in the current directory:

find . -iregex '.*\.\(jpg\|jpeg\|png\|webp\)$' -type f -print0 | xargs -0 -I {} bash -c $'file="{}"\nif [ ! -f "${file%.*}.avif" ]; then\n  echo "Processing: $file"\n  convert "$file" -quality 80 -strip "${file%.*}.avif" && touch -r "$file" "${file%.*}.avif" && echo "✓ Converted to AVIF" && rm "$file"\nelse\n  echo "Skipping: ${file%.*}.avif already exists"\nfi'

Compress videos in the current directory:

# Recursively find videos, convert them to compressed MKV files while preserving their base filenames, downscale videos larger than 1080p, and then delete the originals.
find . -iregex '.*\.\(mts\|m2ts\|mp4\|avi\|mov\|flv\|wmv\)$' -type f -print0 | xargs -0 -I {} bash -c $'file="{}"\necho "Processing: $file"\nif ffmpeg -hide_banner -i "$file" -c:v libx264 -crf 23 -preset medium -vf "scale=min(iw\\,1920):min(ih\\,1080):force_original_aspect_ratio=decrease" -c:a aac -b:a 192k "${file%.*}.mkv"; then\n  touch -r "$file" "${file%.*}.mkv" && echo "✓ Converted" && rm "$file"\nelse\n  echo "✗ Conversion failed: $file"\nfi'

Compress PDF documents in the current directory:

# Compress all PDFs in the current directory, preserve their modification timestamps, and save them in the 'done' folder.
mkdir -p done

for f in ./*.pdf; do
    [ -f "$f" ] || continue

    base=$(basename "$f")

    gs -sDEVICE=pdfwrite \
       -dPDFSETTINGS=/printer \
       -dNOPAUSE -dQUIET -dBATCH \
       -sOutputFile="done/$base" \
       "$f"

    touch -r "$f" "done/$base"
done
Snippet: Batch Compression Commands for Images, Videos, and PDFs
https://blog.juyung.com/posts/en/2026/10/20-1/
Author
Jay Juyung
Published at
2026-10-20
License
CC BY