Hi I'm trying to get the largest number (newest version) of a file,

I got a bunch of tar.gz files in a directory, versions of some software in the format v${version_number}_software.tar.gz, where ${version_number} is a three digit number.

Running ls *.tar.gz | cut -c 2-4 gives me this output:


What would I run next (or what should I change in the ls or cut syntax) to get the highest value (in this case, 705)?

I tried some grep, awk and sed but I'm a bit out of my league... Any clue would be appreciated!

  • Using ls -v will get you most of the way there. – glenn jackman Dec 1 '15 at 14:43

sheesh, I might have noticed that the highest value always comes out to the last line :-)


ls -d -- *.tar.gz | cut -c 2-4 | tail -n 1

it is. Leaving this question on, for posterity

EDIT: but as Lambert has suggested below,

ls -d -- *.tar.gz | cut -c 2-4 |sort -n|tail -n 1

is better to be sure that the output of ls is sorted numerically (otherwise V999.tar.gz could come before v100.tar.gz in locales where the sort order is case-sensitive). Too bad he didn't post it as an answer.

  • 3
    That the highest value always comes last is because of the lexical order. You might consider to force numeric sorting by inserting the command sort -n between the cut.. and tail... commands: ls *.tar.gz | cut -c 2-4 |sort -n|tail -n 1 – Lambert Dec 1 '15 at 13:53
  • 1
    Depending on the format of the version numbers, -V or --version-sort may be a better option than -n or --numeric-sort. Note, though, IIRC -V is only available in GNU sort. – cas Dec 1 '15 at 19:49
  • Hi Lambert, yours is a better solution. you wanna post it as an answer? I can't accept my own answer as correct anyway, before a couple of days have passed – Nahshon paz Dec 3 '15 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.