Is there a way to do:
output | grep "string1" | grep "string2"
BUT with awk, WITHOUT PIPE?
Something like:
output | awk '/string1/ | /string2/ {print $XY}'
Result should be subset of matches, if tha makes sense.
asked Dec 30, 2020 at 14:48
2 Answers 2
The default action with awk
is to print, so the equivalent of
output | grep string1 | grep string2
is
output | awk '/string1/ && /string2/'
e.g.
$ cat tst
foo
bar
foobar
barfoo
foothisbarbaz
otherstuff
$ cat tst | awk '/foo/ && /bar/'
foobar
barfoo
foothisbarbaz
answered Dec 30, 2020 at 15:05
-
1Accepting this answer because of the extra example/ proofRiddleMeThis– RiddleMeThis2020年12月30日 16:06:22 +00:00Commented Dec 30, 2020 at 16:06
-
That is the equivalent of the pipeline the OP provided but if the OP actually wants to match 2 strings instead of 2 regexps then it'd be
awk 'index(0,ドル"string1") && index(0,ドル"string2")
Ed Morton– Ed Morton2021年01月02日 18:31:52 +00:00Commented Jan 2, 2021 at 18:31
If you want awk
to find lines that match both string1
and string2
, in any order, use &&
:
output | awk '/string1/ && /string2/ {print $XY}'
If you want to match either string1
or string2
(or both), use ||
:
output | awk '/string1/ || /string2/ {print $XY}'
answered Dec 30, 2020 at 15:06
-
1Just to note, for anyone who stumbles upon this, what I exactly did was: ps aux | awk ... to keep awk from showing in the result I had to do awk /[s]tring/. Its the same trick used for grep.RiddleMeThis– RiddleMeThis2020年12月30日 15:12:23 +00:00Commented Dec 30, 2020 at 15:12
-
2I think the
{print $XY}
thing is something like a placeholder that the OP thought would be useful/necessary. I believe it is better out of the answer since it doesn't make much sense.Quasímodo– Quasímodo2020年12月30日 15:34:42 +00:00Commented Dec 30, 2020 at 15:34 -
@Quasímodo it makes perfect sense: it is a placeholder for "print field number N" and including it shows what the correct syntax would be, so it can easily be adapted by future users.2021年01月01日 14:37:45 +00:00Commented Jan 1, 2021 at 14:37
default
|
missing :awk '/string1/ || /string2/ {print $XY}'
||
will match any line with either "string1" or "string2", whereas thegrep
s only match lines with both (so&&
in AWK).