Grep – Why Is My Grep Command Not Working?

grep

I have these files:

dd1 contains:

ok
stanley

dd2 contains:

ouddd
eddi

dd3 contains:

hello
dd1

And I used the command

$ grep -E dd* dd1 dd2 dd3

hoping to get all the lines that contained the letter d in them. So I was hoping to get

dd2: ouddd
dd2: eddi
dd3: dd1

but instead I got

dd3:dd1
dd3:dd1

I don't understand why I only got only the last one (dd3:dd1), and also why it gave it to me twice?

Best Answer

The regular expression that you use, dd*, is not quoted at all in the shell. This means that the shell will use it as a filename globbing pattern and will expand it to all matching filenames (dd1, dd2, and dd3).

The command, thus, will be

grep -E dd1 dd2 dd3 dd1 dd2 dd3

This runs grep with the pattern dd1 across the files dd2, dd3, dd1, dd2, and dd3. You get two lines from from the file dd3 because there is one line matching the expression but the file occurs twice in the list of files.

To give the pattern to grep unexpanded by the shell, quote it:

grep 'dd*' dd1 dd2 dd3

or, equivalently,

grep -E 'd+' dd[123]
Related Question