Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

In a directory, I have files like

lazer_100506
lazer_100707
lazer_091211
lazer_110103
lazer_100406_temp
lazer_100622#delete

etc

How can I get a listing of only the first four files?

$ ls lazer_......
ls: lazer_......: No such file or directory
$ 
share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

There are multiple methods:

ls only

ls lazer_??????

ls and egrep

ls | egrep '^lazer_.{6}$'

find

find . -regextype posix-egrep -regex '^./lazer_.{6}$'
share|improve this answer
    
Does ls only recognize * as a wildcard character? –  Lazer Jan 8 '11 at 17:53
    
also accepts ? and [ ] –  wag Jan 8 '11 at 17:59
2  
It's not ls who expands wildcards: it's the shell who does. –  alex Jan 8 '11 at 18:14
2  
@Lazer What you're experiencing is the difference between globbing and regular expressions. Unfortunately, these two grammars share some of the same symbols but they have very different meanings. In regex, the . means any single character but with globs, this is specified by ?. Shells understand globbing, not regex. –  SiegeX Jan 8 '11 at 21:45
1  
In Bash, easy way to type ??????: <Esc> 6 ? or Alt-6 ? –  ephemient Jan 8 '11 at 22:43
add comment

As pointed out by SiegeX, Shell alone does not understand regular expressions. If you want a precise filter of your files, you must use regular expressions and hence use a command like egrep.

Here, the files you want to list begin with lazer_ and are followed only by some digits (possibly more or less that 6). I would do it this way:

ls | egrep '^lazer_[[:digit:]]*$'

This regex works the same as '^lazer_[0-9]*$'.

Regular expressions with egrep also handles repetition just like in the answer of wag, if you want to restrict your list to files ending with exactly 6 digits:

ls | egrep '^lazer_[[:digit:]]{6}$'
share|improve this answer
    
Note that [:digit:] is a POSIX character class. –  Mathieu Chapelle Jan 10 '11 at 10:01
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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