8

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

10

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:

2
-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
2
  • 1
    Do you know what the -in does?
    – annahri
    Feb 1 at 20:38
  • Good examples, but be aware that using the n flag will prepend the line number to each resulting line. Mar 26 at 4:36

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.