1

So I'm learning how powerful shell scripting is and love it, but am having a really hard time with this...

I have a bunch of files named as: checkin.10 checkin.11 checkin.12

The number after the . will always be a # and goes up sequentially.

I need to find all checkin.* files in a dir, and return the file with the highest # in the filename. So for the above files, I would need to return 'checkin.12'. My logic was to get all checkin.* file names, loop through them and compare the # to the # of the previous file stored in a variable. If the current file's # is higher, I update the variable # to be the current files #, if it's lower, I move onto the next one. This way I'm able to get checkin.12 returned as the highest # and do what I need to do with checkin.12. There has to be a better way to do this, was hoping someone could show me an example of another approach.

user797963
  • 2,907
  • 9
  • 47
  • 88

1 Answers1

4
ls checkin.* | sort -t. -n | tail -1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Oh man!! `sort` How did I miss that? I feel dirty now. +1 .. If you'd like to use `head` then `ls checkin.* | sort -t. -rn | head -n +1` or `head -n +1 <(sort -t. -rn <(ls checkin.*))` But nicely done sir! – jaypal singh Jan 10 '12 at 22:29
  • Note that there is a marginal cheat - actually, oversight and carelessness - in the `sort` command; it sorts the first field numerically (which is the name 'checkin', so it always sorts equal and as zero), then the actual numeric suffix. You should be able to marginally improve performance (I'm not sure that you'd be able to measure it) by using `sort -t. -k 2n` (to sort numerically on the second column). The result is the same, this time. Sometimes, I just get lucky. – Jonathan Leffler Jan 11 '12 at 00:14