Reputation: 881
I have a large file that has some regular pattern
snaps1: Counter: 4966
Opens: Counter: 357283
Instance: s.1.aps.userDatabase.mount275668.attributes
snaps1: Counter: 0
Opens: Counter: 357283
Instance: s.1.aps.userDatabase.test.attributes
These line are repeated among other lines above and below. I need to print the snaps1 line and also get the instance: line So I need to search for snaps1 but only if counter is greater than 0 and then print snaps1 line and also the instance line.
Sorry have no clue on how to do this? Can you help?
So from the lines above I should see this output
snaps1: Counter: 4966
Instance: s.1.aps.userDatabase.mount275668.attributes
Appreciate any help you can provide
Upvotes: 1
Views: 60
Reputation: 14965
Try this:
awk '/snaps1/ && $NF>0{print;f=1}f&&/Instance/{print;f=0}' file
To avoid blanks at the beginning of the line:
awk '/snaps1/ && $NF>0{gsub(/^ */,"");print;f=1}
f&&/Instance/ {gsub(/^ */,"");print;f=0}' file
Results
snaps1: Counter: 4966
Instance: s.1.aps.userDatabase.mount275668.attributes
Explanation
/snaps1/ && $NF>0 {gsub(/^ */,"");print;f=1}
is used to set f
flag when snaps1
pattern is found and the last field NF
must be greater than one also deletes unwanted spaces and print current line.
NOTE /snaps1/ && $NF
it's an equivalent expression, the reason: any numeric value except zero is true for awk
.
f&&/Instance/ {gsub(/^ */,"");print;f=0}
if f
flag is True
(1
) and Instance
pattern is found, print the current line (deleting not wanted spaces) an set the flag back to false.
Upvotes: 3
Reputation: 204174
$ awk '/snaps1/{s=$0; c=$NF} /Instance/ && c{print s ORS $0}' file
snaps1: Counter: 4966
Instance: s.1.aps.userDatabase.mount275668.attributes
Upvotes: 2