user788171
user788171

Reputation: 17553

grep with wildcards

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

Upvotes: 5

Views: 18003

Answers (3)

HoaPhan
HoaPhan

Reputation: 1918

It's not very pretty but you can chain the grep together:

grep -l "directory1" ./*.txt|xargs grep -l "directory2"|xargs grep -l "directory3"

Limit your input so to improve performance, for example use find:

find ./*.txt -type f |xargs grep -l "directory1"|xargs grep -l "directory2"|xargs grep -l "directory3"

Upvotes: 1

Kent
Kent

Reputation: 195029

under which shell did you test?

here

grep directory[1-3] works for bash, doesn't work under zsh

you can either quote "directory[1-3]"

or escape grep directory\[1-3\]

bash v4.2
zsh v5.0.2
grep (GNUgrep 2.14)

Upvotes: 2

nneonneo
nneonneo

Reputation: 179392

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).

Upvotes: 10

Related Questions