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?

  • 3
    It is not as much 'wrong' as wasteful. This is gratuitous use of cat. – Hennes May 21 '13 at 5:31
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.

| improve this answer | |
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.

| improve this answer | |
  • 2
    This is a very good answer. – JakeGould Dec 28 '18 at 1:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.