-1

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?

Yurets
  • 3,999
  • 17
  • 54
  • 74
Prasad
  • 3
  • 1
  • 3
  • I'm not sure I understand. Is the issue how to convert an array of filenames into a comma-separated string? I'm further confused by the inclusion of the `dos2unix` tag... – Kusalananda Jun 28 '18 at 13:30
  • If you're on a system with GNU tools, look at `ls -v` and `sort -V` in the respective man pages. – glenn jackman Jun 28 '18 at 13:40
  • @Kusalananda i want it for consolidation .......not comma separated string but seprate array with latest/mentioned values above – Prasad Jun 28 '18 at 13:58

1 Answers1

0

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.

Kusalananda
  • 14,885
  • 3
  • 41
  • 52
  • for i in `cat object.txt` ; do echo $i >> output.txt; grep -i -A 5 $i markingfile.log | egrep -i 'Object Name| Object Type' >> output.txt; done; – Prasad Apr 04 '20 at 04:06