I need to redirect lines from stdout to a file, but just those containing certain string1
or not containing certain string2
. How can I do that? I just know how to do that separatelly (either lines containg a string1
or lines not containing a string2
). It doesn't have to be grep
, just something I can use in a pipe in a terminal.
Add a comment
|
3 Answers
Perl to the rescue!
perl -ne 'print if /string1/ || ! /string2/' < file
-n
reads the input line by line/string1/
is a regex match||
means "or",!
means "not"
You can pipe to awk
:
your_process | awk '$0!~/string2/ || $0~/string1/{print $0}'
If the line being processed does not contain "string2": $0!~/string2/
OR if the line being process does contains "string1": $0~/string1/
Then print the line: {print $0}
As @Mischa shared in the comments, you can get very terse with awk. This can be written as:
your_process | awk '/string1/ || !/string2/'
-
There is
or
in the question notand
, but I just change&&
I guess.– T.PoeCommented Dec 21, 2017 at 20:39 -
{print $0} is the default. For tersaholics: ... | awk '/string1/ || !/string2/'– MischaCommented Dec 21, 2017 at 20:41
-
@T.Poe Sorry about that.
OR NOT
sounds weird and my brain decided it couldn't handle it. Just change that&&
to||
and I think that should work fine for you.– JNevillCommented Dec 21, 2017 at 20:44 -
It doesn't seem to work. When I reditect to the file with
>
it doesn't write anything. Withtee
it writes something but it stops writing after a while (very quickly), I don't understand that. I tried it with just one statement, without OR, still nothing. My command literally looks like this:nohup python ./script.py | awk '!/string/' | tee out.txt
or> out.txt
instead of| tee
.– T.PoeCommented Dec 21, 2017 at 21:03 -
I believe that's due to your
nohup
. Check out this answer for doing a pipe with nohup.– JNevillCommented Dec 21, 2017 at 21:05
You can try something like this:
tail -f {SOMETHING} | grep string1 | grep -v string2 >> /tmp/out.log
-
it is worth to consider "line buffered" output as you are getting input from
tail
and passing it to 2grep
processes. (Hello from Kyiv) Commented Dec 21, 2017 at 21:11 -
@RomanPerekhrest Main idea - is to use
grep string1
for match desired strings andgrep -v string2
to exclude non-interested strings, all the - rest just for sake of example.– cn0047Commented Dec 21, 2017 at 22:01