Compare the following commands:
cat f.txt | grep "someText"
grep "someText" f.txt
They both seem to work. But the documentation for cat says cat outputs the contents of the file rather than the file name and grep command takes file name but not file contents (correct me if I am wrong), then why does the first command work since it is feeding grep with the file contents rather than the file name.
Another question: they both work but why would one use the first line instead of the second, the first one is just redundant?
Best Answer
In your first example
grep
doesn't get a filename argument, only a string to search for. In that casegrep
will read the text to search from standard input. In this case that standard input is piped in from the output ofcat f.txt
, which outputs the content of the file not the filename.What you also could have done to make
grep
read from stdin is to use:Using
cat
is quite often redundant on its own (independent ofgrep
) and can be replaced by the input redirection as above. I would always use the second form in your example, unless you have to do some preprocessing on the input.