Issue
I got a log file where I need to print the first line if a keyword is present in between the patterns.
For example:
LEVEL: X
abc
123
def rty
LEVEL: A
abc
123
LEVEL: Z
abc
def 345 rty
ocp
Search is between pattern "LEVEL" for keyword "def".
Expected Output:
LEVEL: X
LEVEL: Z
Looking use awk or sed, as the log file more than 10000 lines.
I have tried something like
awk '/LEVEL:/{flag=1}/LEVEL:/{print;flag=0}flag' file
But I am not sure how to search for the keyword "def" in the list and print only the matching first line of it.
Update:
awk '/LEVEL:/{flag=1}/def/||/LEVEL:/{print;flag=0}' file
But the output is as such
LEVEL: X
def rty
LEVEL: A
LEVEL: Z
def 345 rty
To be more clear, I am tying to search between 2 consecutive patterns "LEVEL:" the keyword "def".
Any suggestions will be helpful. Thanks.
Solution
awk '
$1=="LEVEL:" {
lvl=$0
next
}
lvl && index($0,"def") {
print lvl
lvl=""
}
' file
This saves the "LEVEL" line so that it can be printed if "def" is found.
Answered By - user14473238 Answer Checked By - Marie Seifert (WPSolving Admin)