Thursday, 7 March 2019

bash - How to use grep to match two strings in the same line

I know some people will disagree, but I think the best way is to do it like this :



Lets say this is your input :



$ cat > fruits.txt
apple banana
orange strawberry
coconut watermelon

apple peach


With this code you can get exactly what you need, and the code looks nicer and cleaner :



awk '{ if ( $0 ~ /apple/ && $0 ~ /banana/ ) 
{
print $0
}
}' fruits.txt



But, as I said before, some people will disagree as its too much typing. ths short way with grep is just concatenate many greps , e.g. :



grep 'apple' fruits.txt | grep 'banana'


Regards!

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 ...