Linux – Why ” grep * ” not working

greplinux

On these days learning linux, I found something confued me:

$ cat abcd
line One
line Two
line Three
$ cat abcd | grep *
$ _                       //nothing greped
$ cat abcd | grep ""
line One
line Two
line Three
$ cat abcd | grep "*"
$ _                       //nothing greped

the "_" is just the cursor, don't get mistake 🙂

who would explain this? Thanks

Best Answer

The glob * is expanded by the shell to an alphabetic list of all (non-dot) the files in the current directory. The arguments to grep are a search expression and a list of files. So grep * ends up using the first file name as the search expression. You are looking for the first file's name (as a regular expression) in the other files.

Grep searches standard input only if you do not supply any explicit file names. See:

echo moo | grep . /etc/issue
Handmade Linux for OS/X v 0.001

Incidentally, * is not a valid regular expression. As you have discovered, an empty search expression matches all input lines. A regular expression which matches all non-empty input lines is .; in regex, the dot is a metacharacter which matches one character, any character except newline. The kleene star is a suffix operator which allows for zero or more repetitions of the previous regular expression, so you frequently see the regex .* for "anything at all", but in this context, it is redundant, as you are already matching nothing at all with the empty search string.

Finally, it is considered bad form to cat a single file. Instead of cat file | grep "" you save a process and perhaps some scorn by having grep read the file directly; grep "" file

Related Question