Search code examples
bashvarcut

bash, find all strings in a var


I'm Making a script to get DAR information out of video file. to do that, I'm using this script with success

DAR=$(ffmpeg -i "$DOSSIER/$OLD_NAME.$EXTENSION" -hide_banner 2>&1 | grep -i -oP "DAR [0-9]+:[0-9]+")
# if DAR not exist set it to 1
if [ -z "$DAR" ];
    then 
        DAR="DAR 1:1"
fi
X_DAR=$(echo "${DAR:4}" | cut -d: -f1)
Y_DAR=$(echo "${DAR:4}" | cut -d: -f2)

My main problem is that sometimes, videos have multiple DAR so my output looks like

echo $DAR
DAR 16:9 DAR 5:4 DAR 234:211

from there, I would need the biggest number of all operations available behind the DAR. and there could be 2 DAR available or 10.

any ideas? thanks


Solution

  • If you want to sort it by the number left to : then do this:

    for((n=1;n<$(echo $DAR | wc -w)+1;n+=2)); do echo $DAR | cut -d' ' -f$n,$(($n + 1)); done | sort -k2 --numeric-sort -r | head -n1
    

    Or if you want to sort it by the number right to : then do this:

    for((n=1;n<$(echo $DAR | wc -w)+1;n+=2)); do echo $DAR | cut -d' ' -f$n,$(($n + 1)); done | sort -t: -k2 --numeric-sort -r | head -n1
    

    Output:

    DAR 234:211
    

    EDIT:

    Now this first divides the two numbers and then sorts them by the result.

    for((n=1;n<$(echo $DAR | sed "s/ /\n/g" | wc -l)+1;n+=2)); do echo $DAR | cut -d' ' -f$n,$(($n + 1)); done | awk -F'[ :]' '{printf "%s %s:%s;%s\n",$1,$2,$3,$2/$3}' | sort -t';' -k2 --numeric-sort | tail -n1 | cut -d';' -f1