Help with selective ls

Hi all

:wall:

Can anyone advise how do I use ls to do a selective amd sorted listing of file that I want to have as below?

Am looking for files that are named as log_<nnnn>.txt, where <nnnn> are numeric, i.e. I want to have a listing sorted from the newest to the oldest of files that starts with log_ and with a .txt extension and the characters in between these two can only be numeric, example log_1.txt, log_234.txt, log_222.txt etc.

I want to exclude files like log_9ab.txt, log_a9b.txt., log_99a.txt

I thought I can get away with doing

ls -1tr log_[0-9][0-9]*.xml

but unfortunately the * list also files like log_99a.txt.

I want to be able to only list files where the characters in between log_ and .txt are numeric, unfortunately, sometimes, there can be 2, 3 or 5 numeric characters.

Any advise will be much appreciated. Thanks in advance.

ls -1tr log_[0-9][0-9]* works as expected on my RHEL GNU-Bash.

An alternative, try this:

ls -1tr | grep 'log_[0-9][0-9]*.txt'

Try:

ls -1tr log_[0-9].xml  log_[0-9][0-9].xml  log_[0-9][0-9][0-9].xml  log_[0-9][0-9][0-9][0-9].xml  log_[0-9][0-9][0-9][0-9][0-9].xml 2>/dev/null 

Less exact, but you might get away with:

ls -1tr log_*[0-9].xml

Try:

ls | egrep 'log_[0-9]+\.xml'
ls log_+([0-9]).txt

(ksh on RHEL 5.4)

ksh93-style extended globbing also works in recent versions of bash after issuing:

shopt -s extglob

Thanks. That one works so far on :Linux. Hope the same thing works on Solaris.

---------- Post updated at 06:27 AM ---------- Previous update was at 06:18 AM ----------

Thanks to everyone who responded.

So far, yazu's suggestion is what am trialing out.

ls | egrep 'log_[0-9]+\.xml' 

Also found the link below useful, in case egrep does not function like it used to on other *nixes or on others where egrep is not available.

FYI, my other chosen alternative which is using awk if egrep is not available is as below. Any awk expert around to make it "shorter"

ls -1tr *.xml | awk -F. '{ print $1 }' | awk -F_ '{ print $2 }' | awk '/^[0-9]+$/' | awk '{ print "log_"$1".xml" }'

or for .txt files

ls -1tr *.txt | awk -F. '{ print $1 }' | awk -F_ '{ print $2 }' | awk '/^[0-9]+$/' | awk '{ print "log_"$1".xml" }'

Thanks again everyone. Very much appreciated.

You can just use the same regex as a pattern as you did for egrep:

ls -1tr *.txt | awk '/log_[0-9]+\.txt/'