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 $
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
There are multiple methods:
ls only
ls lazer_??????
ls and egrep
ls | egrep '^lazer_.{6}$'
find
find . -regextype posix-egrep -regex '^./lazer_.{6}$'
Method 2
With zsh you could use a glob like ?(#cN) (here the c flag requires the previous ? to match exactly N times):
setopt extendedglob print -rl -- ?(#c12)
if you prefer ls:
ls -d -- ?(#c12)
You can also add qualifiers, e.g. search recursively for regular files with fixed name length:
print -rl -- **/?(#c12)(.)
Method 3
With ksh93:
printf '%sn' {12}(?)
for (non-hidden) files whose name are made of 12 characters.
Or if you prefer regular expressions:
printf '%sn' ~(E)^.{12}$
Method 4
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}$'
Method 5
Another solution is to use echo command.
echo lazer_??????
Note that regular expression handling is done by whatever shell the echo command is running within.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0