Please use ***[code][/code] tags
*** around your code and data, to preserve formatting and to improve readability. Please do not
use quote tags, colors, or other fancy formatting.
In bash, you can also exclude files using a simple extended globbing
shopt -s extglob #It's not enabled by default
echo !(*.gz) #Glob patterns can be used with almost any command,
#as they're expanded by the shell before execution.
Originally Posted by Didier Spaier
For grep, * means "match what follows zero or more times".
Huh? It means no such thing. grep
uses regular expressions
in its pattern matching, and in regex, "*
" means "match the previous character zero or more times
" is thus not
a valid regular expression (there's no previous character), although it is a valid globbing pattern. The regex equivalent for that glob pattern is "^.*\.gz$
" in regex means "any character
" is start of line
", and "$
" is "end of line
". Note that the second period has to be backslash-escaped to make it literal.
Actually, the "^.*
" part is really not necessary since the expression is anchored to the end of the line, so "\.gz$
" is equivalent.
" used above does also work for the most part, but do be aware that it will match any
string that ends in "gz", e.g. "thingz".
Learning how to properly use regular expressions is one of the best bang-for-the-buck subjects you can spend your time on. A very large number of programs support, or even depend on, them.
Here are a few regular expressions tutorials:
Finally, be aware that parsing ls
is generally not
recommended. Use globbing patterns for simple file matching, and find
for more complex ones, although it usually takes a bit more work to handle find's output safely
Edit: One more point. Unlike shell globbing, find
searches recursively, so it would return all matching files in subdirectories as well. Use the -maxdepth
option to restrict it to the current directory only, as demonstrated by suicidaleggroll. Also, be aware that the -name
options use globbing patterns (but not bash's extended globs). There's a separate set of -regex
options if you need more sophisticated pattern matching.
Here are a couple of good links about using find: