SED AWK to strip data from log file

114 views Asked by At

Hi I have the following entries in log file. I need to produce a list of names in the name field if I see Denied on the line above. So I need to get something like:

Sally
Matt

Linda

Can you help me with this and I would appreciate if you could explain the command so I can use it later on for other logs.

<!-- user 1 -- >
<ABC  12345 "123" text="*Denied: ths is aa test status="0" > 
   <key flags="tdst"  name="sally"  />
<userbody>
</Status>

<!-- user 2 -- >
<ABD  12345 "123" text="*Denied: ths is aa test status="0" > 
  <key flags="tdst"  name="Matt"  />
<userbody>
</Status>

<!-- user 3 -- >
<ABD  12345 "123" text="*Denied: ths is aa test status="0" > 
   <key flags="tdst"  name="Linda"  />
<userbody>
</Status>

Regards

2

There are 2 answers

2
josifoski On BEST ANSWER

This GNU sed could work

sed -n -r '/Denied:/{N; s/^.*name="([^"]*)".*$/\1/; p}' file  

n is skip printing lines
r using extended regular expressions, used for grouping here, to not escape () characters
N is reading next line and adding it to pattern space
s/input/output/ is substitution
^ is start of line, so ^.*name=" will find everything till [^"] first next quote.
$ is end of line
[^"] is any character which is not " (set negation)
\1 is taking only matching group i.e. ([^"]*)
p is printing line (when prev condition Denied is fullfiled on processed 2 lines

output

sally
Matt
Linda
0
NarūnasK On

Try this:

sed -rn '/Denied/{n;s#(.+)(name="(\w+))"(.+)#\3#p}' < sample.txt

/Denied/ - search for the keyword
{n; - if found then read next line
s#(.+)(name="(\w+))"(.+)#\3#p - lookup regex groups and print out only the third one, which is equal to the name within quotes in your data sample.