0cd
0cd

Reputation: 1869

Filtering output lines that are between certain lines

I've a command that I launch from the bash shell, that outputs a whole bunch of lines.

I want to see all it's output except the lines between lines "Looking for changes" and "Waiting for changes from server"

So let's say the actual output is -

Line 1
Line 2
Looking for changes
Line 3
Line 4
Waiting for changes from server
Line 5
Line 6

I want to only see -

Line 1
Line 2
Looking for changes
Waiting for changes from server
Line 5
Line 6

I could write a quick python script that I can pipe this through but was wondering if it could be done with something out of the box, like grep or awk.

Upvotes: 1

Views: 351

Answers (2)

fedorqui
fedorqui

Reputation: 289835

I came out with this solution:

$ sed -n -e '1,/Looking/p' -e '/Waiting/,$p' file
Line 1
Line 2
Looking for changes
Waiting for changes from server
Line 5
Line 6
  • '1,/Looking/p' prints from the beginning of the file up to the line containing Looking.
  • '/Waiting/,$p' prints from the line containing Waiting up to the end of the file.
  • sed -e is the way to make sed execute different blocks: sed -e 'something' -e 'other thing'.

Upvotes: 3

user000001
user000001

Reputation: 33327

Here is an awk one liner:

... | awk '/^Waiting for changes from server$/{p=0}p==0{print}/^Looking for changes$/{p=1}'

we use the variable p as a flag. If it is zero, we print the line, otherwise we don't. The flag changes value when we match the lines specified.

Upvotes: 1

Related Questions