How to print line if two lines above it matches patterns.?

Hi,

I could only find examples to print line before/after a match, but I'd need to print line after two separate lines matching.

E.g.: From the below log entry, I would need to print out the 1234. This is from a huge log file, that has a lot of entries with "CLIENT" and "No" entries (+ other messages), and I need to print the client number only if the "CLIENT" and "No" tags are in consecutive lines as in the below example.

Would anyone have idea how to do this (awk/sed/?)

....
[12:16:30.901]  <CLIENT>
[12:16:30.901]          <No>
[12:16:30.901]          1234
[12:16:30.901]          </No>
[12:16:30.901]  </CLIENT>
....

Let me try to help with my limited knowledge :smiley:

grep -B1 No log_file | grep -A2 CLIENT | tail -n1

Try that. Hope it helps.
Regards

Try sed:

sed -n '/<CLIENT>/{n;/<No>/{n;p;};}' file

output:

[12:16:30.901]          1234

---
Edit: or a fun awk:

awk '/<CLIENT>/ && getline && /<No>/ && getline' file

Perhaps you want something like:

awk '
$2 == "<CLIENT>" {
	m = 1
	next
}
m == 1 && $2 == "<No>" {
	m = 2
	next
}
m == 2 {print $2
}
{	m = 0
}' file

If file contains:

[12:16:30.901]  <CLIENT>
[12:16:30.901]          <No>
[12:16:30.901]          1234
[12:16:30.901]          </No>
[12:16:30.901]  </CLIENT>
[12:16:30.901]  <CLIENT>
[12:16:30:901]          <NotNo>
[12:16:30.901]          1235
[12:16:30.901]          </NotNo>
[12:16:30.901]  </CLIENT>
[12:16:30.901]  <CLIENT>
[12:16:30:901]          <NotNo>
[12:16:30.901]          1236
[12:16:30.901]          </NotNo>
[12:16:30.901]          <No>
[12:16:30.901]          1237
[12:16:30.901]          </No>
[12:16:30.901]  </CLIENT>
....

it produces the output:

1234

which, I believe, matches what you said you wanted.

If you want to try this on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk or nawk .