ls | sort -n -t _ -k 2 | tail -1
assuming the [RANGE] portion could be anything:
- Directory: /incoming/external/data
- File format: [RANGE]_[YYYYMMDD].dat
Tools:
We don't need sed, since we can work with the entire output of ls command. Using ls, awk, sort, and tail we can get the correct file (check syntax against what your OS accepts):
NEWESTFILE=`ls | awk -F_ '{print $1 $2}' | sort -n -k 2,2 | tail -1`
Then it's just a matter of putting the underscore back in.
EDIT: I had a little time, so I got around to fixing the command, at least for Solaris.
Here's the convoluted first pass (this assumes that ALL files in the directory are in the same format: [RANGE]_[yyyymmdd].dat). I'm betting there are better ways to do this, but this works with my own test data (in fact, I found a better way just now; see below):
ls | awk -F_ '{print $1 " " $2}' | sort -n -k 2 | tail -1 | sed 's/ /_/'
... while writing this out, I discovered that you can just do this:
ls | sort -n -t _ -k 2 | tail -1
I'll break it down.
ls
gets the directory listing, just filenames. Now pipe that into the next command:
awk -F_ '{print $1 " " $2}'
awk allows you to take an input line and modify it. All I'm doing is specifying that awk should break the input wherever there is an underscore (_) with the -F
answered 2010-08-16T17:56:06.990