Shell Script to Identify Only Audio Files from yt-dlp Downloads Using ffmpeg's ffprobe and Move Them to a Separate Directory

4 min

language: ja bn en es hi pt ru zh-cn zh-tw

ffprobe.png

Hello, it's me, the incompetent one.

I've completely self-managed my favorite YouTube videos using yt-dlp.

However, because I didn't include a check for music.youtube.com when saving, everything is in the same directory.
With this, music and other content are mixed, making it very difficult to view, so I came up with a way to somehow separate the folders.


So, it's impossible to distinguish between regular video files and music files if they have the same .mp4 extension.
Even if I try to determine by file size or length, the accuracy is too low.

Therefore, I realized that I could determine it by aspect ratio.
Surprisingly, ffmpeg can determine the aspect ratio, so I'll check with the following command.

ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=s=x:p=0 “音楽ファイル.mp4”

> 1080x1080

So, it seems to be a 1080 square.

In other words, I just need to move files that output this value to a separate directory.
Wow, ffmpeg is really amazing, isn't it? To think it has such a feature... It's incredible.

So, I've written the shell script as follows.

vi mvfile.sh

#!/bin/bash

# Set directory paths
input_dir="/media/aaa"
output_dir="/media/bbb"

# Create the output directory if it doesn't exist
mkdir -p "$output_dir"

# Process each file
for file in "$input_dir"/*.mp4; do
# Get video aspect ratio using ffprobe
    ratio=$(ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=s=x:p=0 "$file")

    # If the aspect ratio is 1080x1080, move the file to the output directory
    if [ "$ratio" == "1080x1080" ]; then
        mv "$file" "$output_dir"
        echo "Moved $file to $output_dir"
    fi
done

Then, I'll grant execute permissions.

chmod +x mvfile.sh

And then, execute.

./mvfile.sh

With this, if output showing movement appears, it's a success.
It might be a good idea to set the above script as a cron job for the directory used for saving video files.

That's all for now.

Looking forward to your continued support.

※Note: It seems there are many thumbnails that are slightly off, so I changed the thumbnail detection as follows.

if [[ "$ratio" == @(10[78][0-9]x10[78][0-9]|7[12][0-9]x7[12][0-9]) ]]; then

Related Posts