Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write output out of grep into a file on Linux?

Tags:

linux

grep

find . -name "*.php" | xargs grep -i -n "searchstring" >output.txt

Here I am trying to write data into a file which is not happening...

like image 247
Rajesh Avatar asked Dec 21 '10 10:12

Rajesh


People also ask

How do I save output to a file in Linux?

Method 1: Use redirection to save command output to file in Linux. You can use redirection in Linux for this purpose. With redirection operator, instead of showing the output on the screen, it goes to the provided file. The > redirects the command output to a file replacing any existing content on the file.

How do you pipe a grep output?

grep is very often used as a "filter" with other commands. It allows you to filter out useless information from the output of commands. To use grep as a filter, you must pipe the output of the command through grep . The symbol for pipe is " | ".

How do I print a grep filename?

grep -n 'string' filename : Force grep to add prefix each line of output with the line number within its input file. grep --with-filename 'word' file OR grep -H 'bar' file1 file2 file3 : Print the file name for each match.


2 Answers

How about appending results using >>?

find . -name "*.php" | xargs grep -i -n "searchstring" >> output.txt

I haven't got a Linux box with me right now, so I'll try to improvize.

the xargs grep -i -n "searchstring" bothers me a bit.

Perhaps you meant xargs -I {} grep -i "searchstring" {}, or just xargs grep -i "searchstring"?

Since -n as grep's argument will give you only number lines, I doubt this is what you needed.

This way, your final code would be

find . -name "*.php" | xargs grep -i "searchstring" >> output.txt
like image 148
darioo Avatar answered Sep 29 '22 01:09

darioo


find . -name "*.php" -exec grep -i -n "function" {} \;  >output.txt

But you won't know what file it came from. You might want:

find . -name "*.php" -exec grep -i -Hn "function" {} \;  >output.txt

instead.

like image 45
Keith Avatar answered Sep 29 '22 01:09

Keith