How can I simplify this command in Linux consisting of cat piped to a grep?

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?

Belmark Caday

Posted 2013-05-21T05:05:28.010

Reputation: 343

3It is not as much 'wrong' as wasteful. This is gratuitous use of cat. – Hennes – 2013-05-21T05:31:51.383

Answers

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.

Patrice Levesque

Posted 2013-05-21T05:05:28.010

Reputation: 780

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.

Jim L.

Posted 2013-05-21T05:05:28.010

Reputation: 669

2This is a very good answer. – JakeGould – 2018-12-28T01:54:22.457