11

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

2 Answers2

13

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" (or sometimes "UUoC"), 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.


Related:

Kusalananda
  • 333,661
  • It's a personal preferrence, but I would like to see a space around redirection symbol. – Vlastimil Burián Oct 07 '17 at 07: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: http://pubs.opengroup.org/onlinepubs/9699919799.2016edition/utilities/V3_chap02.html#tag_18_07 – Kusalananda Oct 07 '17 at 07:17
-1

For searching in a file and writing the result in "path/storage_file":

grep -in pattern file > path/storage_file

For searching in a file and appending (use >>) the result in "path/storage_file":

grep -in pattern file >> path/storage_file

For searching in an entire directory and writing the result in "path/storage_file":

grep -in pattern * > path/storage_file

For searching in an entire directory and appending (use >>) the result in "path/storage_file":

grep -in pattern * >> path/storage_file