Reputation: 13
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.
Upvotes: 1
Views: 63
Reputation: 58420
This might work for you (GNU sed):
sed -n '/^LEVEL/h;/def/{x;p}' file
This is a filtering operation so turn off implicit printing -n
.
Make a copy of each line beginning LEVEL
.
If a line contains def
print the last copy.
Upvotes: 0
Reputation: 37404
In GNU awk using RT
:
$ gawk -v RS="LEVEL[^\n]+" '/def/{print p}{p=RT}' file
Output:
LEVEL: X
LEVEL: Z
Another:
$ awk '/^LEVEL/ {
if(f)
print p
f=""
p=$0
next
}
/def/ {
f=1
}
END {
if(f)
print p
}' file
Upvotes: 1
Reputation:
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.
Upvotes: 3