Saturday 10 November 2018

How to grep for two words existing on the same line?




How do I grep for lines that contain two input words on the line? I'm looking for lines that contain both words, how do I do that? I tried pipe like this:




grep -c "word1" | grep -r "word2" logs


It just stucks after the first pipe command.



Why?


Answer



Why do you pass -c? That will just show the number of matches. Similarly, there is no reason to use -r. I suggest you read man grep.




To grep for 2 words existing on the same line, simply do:



grep "word1" FILE | grep "word2"


grep "word1" FILE will print all lines that have word1 in them from FILE, and then grep "word2" will print the lines that have word2 in them. Hence, if you combine these using a pipe, it will show lines containing both word1 and word2.



If you just want a count of how many lines had the 2 words on the same line, do:



grep "word1" FILE | grep -c "word2"



Also, to address your question why does it get stuck : in grep -c "word1", you did not specify a file. Therefore, grep expects input from stdin, which is why it seems to hang. You can press Ctrl+D to send an EOF (end-of-file) so that it quits.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...