Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep with wildcards

Tags:

grep

wildcard

I would like to grep for the following strings in a file:

directory1
directory2
directory3

Is there a way to grep for all 3 simultaneously with grep?

For instance:

cat file.txt | grep directory[1-3]

Unfortunately, the above doesn't work

like image 289
user788171 Avatar asked Dec 26 '22 09:12

user788171


1 Answers

If those are the only strings you need to search for, use -F (grep for fixed strings):

grep -F "directory1
directory2
directory3" file.txt

If you want to grep using more advanced regex, use -E (use extended regex):

grep -E 'directory[1-3]' file.txt

Note that some greps (like GNU grep) won't require -E for this example to work.

Finally, note that you need to quote the regex. If you don't, your shell is liable to expand the regex according to pathname expansion first (e.g. if you have a file/directory called "directory1" in the current directory, grep directory[1-3] will be turned into grep directory1 by your shell).

like image 140
nneonneo Avatar answered Jan 13 '23 12:01

nneonneo