Last active
April 23, 2025 18:47
-
-
Save gigabyteservice/777ba48c1ffb16925ad099ec54061bfa to your computer and use it in GitHub Desktop.
Download youtube video and trim
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Ask for YouTube URL | |
read -p "Enter YouTube video URL: " YT_URL | |
# Get the video title from yt-dlp | |
echo "Fetching video title..." | |
TITLE=$(yt-dlp --get-title "$YT_URL") | |
# Replace spaces with underscores for a safe base name | |
BASENAME="${TITLE// /_}" | |
echo "Downloading: $TITLE" | |
yt-dlp "$YT_URL" -o "${BASENAME}.%(ext)s" | |
# Find downloaded file with matching base name | |
echo "Looking for downloaded file..." | |
VIDEO_FILE=$(ls | grep "^$BASENAME\." | head -n 1) | |
if [[ -z "$VIDEO_FILE" ]]; then | |
echo "Error: Downloaded file not found." | |
exit 1 | |
fi | |
echo "Downloaded file found: $VIDEO_FILE" | |
# Ask user if they want to trim | |
read -p "Do you want to trim the video? (yes/no): " TRIM | |
if [[ "$TRIM" =~ ^[Yy][Ee][Ss]$ ]]; then | |
read -p "Enter start time (in seconds or HH:MM:SS): " START | |
read -p "Enter end time (in seconds or HH:MM:SS): " END | |
# Function to convert HH:MM:SS to seconds | |
time_to_seconds() { | |
if [[ "$1" =~ ^([0-9]+):([0-9]+):([0-9]+)$ ]]; then | |
echo $((10#${BASH_REMATCH[1]} * 3600 + 10#${BASH_REMATCH[2]} * 60 + 10#${BASH_REMATCH[3]})) | |
elif [[ "$1" =~ ^([0-9]+):([0-9]+)$ ]]; then | |
echo $((10#${BASH_REMATCH[1]} * 60 + 10#${BASH_REMATCH[2]})) | |
elif [[ "$1" =~ ^[0-9]+$ ]]; then | |
echo "$1" | |
else | |
echo "Invalid time format" >&2 | |
exit 1 | |
fi | |
} | |
START_SECONDS=$(time_to_seconds "$START") | |
END_SECONDS=$(time_to_seconds "$END") | |
DURATION=$((END_SECONDS - START_SECONDS)) | |
EXT="${VIDEO_FILE##*.}" | |
TRIMMED_FILE="${BASENAME}-trimmed.${EXT}" | |
echo "Trimming video from $START_SECONDS to $END_SECONDS..." | |
ffmpeg -ss "$START_SECONDS" -t "$DURATION" -i "$VIDEO_FILE" -y -c copy "$TRIMMED_FILE" | |
echo "Trimmed video saved as: $TRIMMED_FILE" | |
else | |
echo "Skipping trimming." | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment