Saturday, July 19, 2008

Listing file names in a numeric range - bash


This looks to be simple, but very important.

In a directory, I had 1000 files, something like:


$ ls -l | awk 'NR!=1{print $NF}' | sort -t "." -nk2


Output:
nsplog.1.log
nsplog.2.log
nsplog.3.log
nsplog.4.log
nsplog.5.log
nsplog.6.log
..
..
nsplog.12.log
nsplog.13.log
nsplog.14.log
..
..
nsplog.997.log
nsplog.998.log
nsplog.999.log
nsplog.1000.log


To list the files from nsplog.500.log to nsplog.599.log

$ ls nsplog.5[0-9][0-9].log


To list the files from nsplog.550.log to nsplog.599.log

$ ls nsplog.5[5-9][0-9].log

.

4 comments:

Alex said...

This technique seems to break down a bit when you need to grab items in a range of say, 25-35. I guess you could do something like 2[5-9]|3[0-5] but do you know of a more general purpose technique?

fietronic said...

A much simpler method is:
npslog.{500..599}.log
npslog.{25..35}.log
etc

-fie

Jadu Saikia said...

@fietronic, thanks.

Jay Smith said...

@fietronic, thanks.

© Jadu Saikia www.UNIXCL.com