Which grep command can I use get two different strings which should appear in the same row?
I do know only how to search for one string by
grep "String"
In this case the string can be present somewhere in the whole file.
CodePudding user response:
The powerful solution is: use grep -e ...
, and build a regexp. That allows you to express much more than just "both strings occur on the same line", e.g. you can specify their order, or additional constraints.
The simple solution for finding lines that contain two strings (in any order) is to pipe the result of one grep
to the other, e.g.:
grep "foo" file.txt | grep "bar"
CodePudding user response:
There are two ways for find two strings, using grep
:
Search for "a" AND "b" inside one line:
grep "a" file.txt | grep "b"
Search for "a" OR "b" inside one line:
egrep "a|b" file.txt
CodePudding user response:
I am assuming youre trying to match the cases where both strings are present in a single line. if so:
if you just want the matches use:
grep -E '^.*string1.*string2.*$'
if the strings dont have to be in a specific order specify both of them:
grep -E '^.*(string1.*string2|string2.*string1).*$'
if you also want to capture them you have to use sed:
sed -n 's/^.\*\(string1\).\*\(string2\).\*$/\1,\2/gp'