0
How can I simplify this command in Linux consisting of cat piped to a grep.
cat foo*.txt | grep cow
I was told that this is the wrong way to do this. Why is that?
0
How can I simplify this command in Linux consisting of cat piped to a grep.
cat foo*.txt | grep cow
I was told that this is the wrong way to do this. Why is that?
6
You can pass filenames to grep:
grep cow foo*.txt
It's “wrong” because you're using cat when you don't need it, really.
3
With respect for the work of the previous authors, I would point out that the two commands do (slightly) different things. The OP's command concatenates all foo*.txt files, and searches the concatenated result once to see whether the string 'cow' appears. @Patrice Levesque's command performs N searches, one for each of the N matching files.
While admittedly obscure and contrived, it is possible to create cases where the OP's command works and the non-gratuitous command fails:
$ for C in w c o; do printf '%s' "$C" > foo-$C.txt; done
$ grep cow foo*.txt
$ cat foo*.txt | grep cow
cow
$ rm foo*
$ printf "wilco" > foo-1.txt
$ cp foo-1.txt foo-2.txt
$ grep cow foo*.txt
$ cat foo*.txt | grep cow
wilcowilco
My point is that it may not be the wrong way to do it, depending on what it is that you're trying to do.
2This is a very good answer. – JakeGould – 2018-12-28T01:54:22.457
3It is not as much 'wrong' as wasteful. This is gratuitous use of cat. – Hennes – 2013-05-21T05:31:51.383