how to fetch file with highest version number and store it in a array.

1 Answer 1


Put all the file names in an array. You didn't specify how you're defining the set of file names you're interested in. I assume that they have a common prefix and suffix. Make an array with all the file names.


If all the version numbers have the same length, which seems to be the case in your example since the numbers have leading zeros, then the file with the highest version number is the last element of the array. The number of elements in the array is ${#all[@]}, and arrays are numbered from 0, so the last element is number $((${#all[@]}-1)).


If the version numbers don't have the same length, it's usually most convenient to use sort to sort them. I'll assume there are no newlines in the file names. Here I isolate the file name as the part before the first ., but only after the last _ before the first ..

highest_version=$(printf '%s\n' abc_efg_2015_hanshake_*.csv.gz |
                  sed -e 's/\..*//' -e 's/.*_//' |
                  sort -n | tail -n1)
  • @Kira ls is not useful here. It's unable to filter files with the right prefix. ls abc_efg_2015_hanshake_*.csv.gz is just a way to do printf '%s\n' abc_efg_2015_hanshake_*.csv.gz except that depending on the system and on the file names it can mangle the file names. Did you think ls was useful because it sorts the file names? It isn't (unless you sort by attributes such as the time or size): wildcard expansion also sorts the files. Commented Dec 19, 2015 at 23:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .