How to a grep a word from a file and store it into another existing file?

What I've tried is

cat q1.txt | grep -i "osx" test.txt

I want to grep it from test.txt and store it into q1, but this and the other way around doesn't work


You may drop the cat completely, and then you should redirect the output from grep to the result file:

grep -i "osx" test.txt >q1.txt

This will search for lines in test.txt containing the string osx (case-insensitively), and store those lines in q1.txt. If the file q1.txt exists, it will be truncated (emptied) before the output is stored in it.

If you wish to append the output at the end of the file, use >> rather than > as the redirection operator.

Your command:

cat q1.txt | grep -i "osx" test.txt

What this actually does is to start cat and grep concurrently. cat will read from q1.txt and try to write it to its standard output, which is connected to the standard input of grep.

However, since you're giving grep a file to read from, it will totally ignore whatever cat is sending it.

In the end, all lines in test.txt that contains the string osx will be outputted to the terminal.

There is something often referred to as "useless use of cat", which means that a cat invocation may be completely removed and that the file may instead be read directly by another tool.

The extreme example of that would be:

cat test.txt | cat | cat | cat | grep -i "osx" | cat | cat >q1.txt

but even just

cat test.txt | grep -i "osx" >q1.txt

is useless as grep is perfectly capable of reading from a file by itself (as seen above). Even if it wasn't able to open test.txt by itself, one could have written

grep -i "osx" <test.txt >q1.txt

to say that standard input should come from the test.txt file and that standard output should go to the q1.txt file

Use cat only when concatenating data (that's what its main use is). There are a few other uses of cat too, but it's outside the scope of this question.


  • 3
    If you however want to append the lines rather than overwriting q1.txt you should use >>q1.txt instead. – dessert Oct 7 '17 at 6:24
  • It's a personal preferrence, but I would like to see a space around redirection symbol. – LinuxSecurityFreak Oct 7 '17 at 7:03
  • @Vlastimil Yes, that's a personal preference. I tend to not put a space in-between them since they "belong together". The POSIX standards document on redirection also does not put a space in-between: pubs.opengroup.org/onlinepubs/9699919799.2016edition/utilities/… – Kusalananda Oct 7 '17 at 7:17

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.