Skip to content

Instantly share code, notes, and snippets.

@pranshuthegamer
Last active June 29, 2023 09:28
Show Gist options
  • Save pranshuthegamer/2493d5107f2317393476ea0dddb38da3 to your computer and use it in GitHub Desktop.
Save pranshuthegamer/2493d5107f2317393476ea0dddb38da3 to your computer and use it in GitHub Desktop.
Take out different parts of a video and join them together
#!/bin/sh
HELP="ffmpeg trimmer script made by pranshutg 12345qwertyman12345@gmail.com
Usage:
-h --help calls this help function
-t --timestamps give this arg a string of times like \"60-2:00 125-130\" and it will extract those two parts
-i --input input file to perform operation on
-s --store specify directory to store trimmed clips in
-k --keep dont delete / keep tmp directory
tips:
./<script> -s /tmp/foobar -i <input_file> -t \"2-60 1:30 2:45\" "
TMPSTORE=0;
KEEP=0;
# Parsing opts
for i in "$@"; do
echo $i
case $i in
"-t"|"--timestamps")
TIMESTAMPS="$2";
shift 2;;
"-h"|"--help")
echo "$HELP";
shift 1;
exit;;
"-i"|"--input")
INPUT="$2";
shift 2;;
"-s"|"--store")
TMPSTORE=1;
TMPDIR="$2";
shift 2;;
"-k"|"--keep")
KEEP=1;
shift 1;;
"")
echo "no args given" $'\n'"$HELP";
exit;;
esac
done
# checks
if [[ $INPUT == "" ]]; then
echo "no input file given";
exit 1;
elif [[ $TIMESTAMPS == "" ]]; then
echo "no timestamps given to extract";
exit 1;
fi
# make tmp dir
if [[ "$TMPSTORE" == 0 ]]; then TMPDIR="${INPUT}_tmp"
fi
rm -rf "$TMPDIR"
mkdir "$TMPDIR"
mins_to_secs () {
if [[ "$1" =~ .*:.* ]]; then
# interpret as base 10: "10#"
$(((10#${1%:*}*60)+10#${1##*:}))
else
echo $1
fi
}
OLDIFS="$IFS"
IFS=" "
index=0
for i in $TIMESTAMPS; do
# get start and end of timestamp given in loop
start=${i%-*};
start=$(mins_to_secs $start);
end=$((${i##*-}-$start));
end=$(mins_to_secs $end);
echo "extracting from $start to $end";
ffmpeg -ss "$start" -t "$end" -i "$INPUT" -c copy "$TMPDIR/$index-$INPUT"
echo file \'$TMPDIR/$index-$INPUT\' >> "$TMPDIR"/concat.txt
index=$((index+1))
done;
ffmpeg -y -f concat -safe 0 -i "$TMPDIR/concat.txt" -c copy "${INPUT%.*}-trimmed.${INPUT##*.}"
if [ $KEEP -eq 0 ]; then rm -r "$TMPDIR"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment