Search code examples
shellshdos2unix

File name with versions comparison in shell script


Suppose I have file names like abc-1.0.sh,xyz-1.0.sh,pqr-1.0.sh,abc-2.0.sh, abc-3.0.sh.

I am trying with array concept, but not able to do it. I want file names as abc-3.0.sh,xyz-1.0.sh,pqr-1.0.sh only. How should I do it in .sh file?


Solution

  • This is a bash script (requires bash 4.3+) that does approximately what you're wanting to do:

    filenames=( abc-1.0.sh xyz-1.0.sh abc-3.1.sh pqr-1.0.sh abc-2.0.sh abc-3.10.sh )
    
    declare -A suffixes majors minors
    
    for filename in "${filenames[@]}"; do
        stem=${filename%%-*}        # "abc-xx.yy.sh" --> "abc"
        suffix=${filename#*-}       # "abc-xx.yy.sh" --> "xx.yy.sh"
    
        # Figure out major and minor version from "$suffix"
        major=${suffix%%.*}         # "xx.yy.sh" --> "xx"
        minor=${suffix#*.}          # "xx.yy.sh" --> "yy.sh"
        minor=${minor%%.*}          # "yy.sh" --> "yy"
    
        if [ -z "${suffixes[$stem]}" ] ||
           [ "$major" -gt "${majors[$stem]}" ] ||
           ( [ "$major" -eq "${majors[$stem]}" ] &&
             [ "$minor" -gt "${minors[$stem]}" ] )
        then
            suffixes[$stem]=$suffix
    
            # Remember the largest parsed "xx.yy" for this stem
            majors[$stem]=$major
            minors[$stem]=$minor
        fi
    done
    
    for stem in "${!suffixes[@]}"; do
        printf '%s-%s\n' "$stem" "${suffixes[$stem]}"
    done
    

    This script outputs

    pqr-1.0.sh
    xyz-1.0.sh
    abc-3.10.sh
    

    It parses the filenames and extracts the stem (the bit before the dash) and the suffix (the bit after the dash), then it extracts the major and minor version from the suffix. It then uses a set of associative arrays, suffixes, majors and minors, to compare the version components with the previously found latest version for that particular stem. If the stem has not been seen before, or if the version of the seen stem was lower, the arrays are updated with the information for that stem.

    At the end, the consolidated data is outputted.

    The restriction in this code is that the filename always is on the form

    stem-xx.yy.something
    

    and that xx and yy are always integers.