-2

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.

3 Answers 3

0

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"
0

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/' 
5
  • There is or in the question not and, but I just change && I guess.
    – T.Poe
    Commented Dec 21, 2017 at 20:39
  • {print $0} is the default. For tersaholics: ... | awk '/string1/ || !/string2/'
    – Mischa
    Commented 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.
    – JNevill
    Commented Dec 21, 2017 at 20:44
  • It doesn't seem to work. When I reditect to the file with > it doesn't write anything. With tee 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.Poe
    Commented Dec 21, 2017 at 21:03
  • I believe that's due to your nohup. Check out this answer for doing a pipe with nohup.
    – JNevill
    Commented Dec 21, 2017 at 21:05
0

You can try something like this:

tail -f {SOMETHING} | grep string1 | grep -v string2 >> /tmp/out.log
2
  • it is worth to consider "line buffered" output as you are getting input from tail and passing it to 2 grep processes. (Hello from Kyiv) Commented Dec 21, 2017 at 21:11
  • @RomanPerekhrest Main idea - is to use grep string1 for match desired strings and grep -v string2 to exclude non-interested strings, all the - rest just for sake of example.
    – cn0047
    Commented Dec 21, 2017 at 22:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.