Grep with wildcards

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

directory1
directory2
directory3

      

Is there a way to grep all 3 at the same time with grep?

For example:

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

      

Unfortunately the above doesn't work

+3


source to share


3 answers


If these are the only lines you need to find, then use -F

(grep for fixed lines):

grep -F "directory1
directory2
directory3" file.txt

      

If you want to grep using a more extended regex, use -E

(use an extended regex):



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

      

Note that for some grep

(like GNU grep) this example is not required -E

.

Finally, note that you need to quote the regex. If you do not, your shell will be subject to regex expansion according to the pathname expansion (for example, if there is a file / directory named "directory1" in the current directory, it grep directory[1-3]

will be turned into grep directory1

your shell).

+6


source


under which shell did you check?

here

grep directory[1-3]

works for bash, doesn't work for zsh



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

or escape grep directory\[1-3\]

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

      

0


source


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

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

      

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

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

      

0


source







All Articles