0
votes

I want to use awk to print 5 lines before and 5 lines after the match regex (Start in ERROR and finish with on of INFO |WARN |DEBUG|TRACE). Also, I need to print the line number as well. I just success to print the line number

cat  foo |  awk '/\[ERROR\]/,/\[(INFO |WARN |DEBUG|TRACE)/{print NR":"$0}'

I don't care to find a solution with grep command

For example, the file contains:

DEBUG
DEBUG
DEBUG
TRACE
TRACE
INFO 
INFO 
ERROR
INFO 
INFO 
INFO 
DEBUG
DEBUG
DEBUG
DEBUG

The output should be:

3: DEBUG
4: TRACE
5: TRACE
6: INFO 
7: INFO 
**8: ERROR
9: INFO** 
10: INFO 
11: INFO 
12: DEBUG
13: DEBUG
14: DEBUG

The stars mark the match regex(Begin in ERROR, end in INFO)

3
Please add sample input (no descriptions, no images, no links) and your desired output for that sample input to your question (no comment) - Cyrus
grep -n -A5 -B5 ERROR file.txt - Jetchisel
grep -n -A5 -B5 ERROR file.txt | sed 's/:/: /;s/-/: /' - Jetchisel
will you always have at least 5 lines before/after the start pattern ('ERROR' in this example)? can you have more than one 'ERROR' in the file? what would you expect as output if there are 2x 'ERROR' patterns and less than 10 lines between them? - markp-fuso

3 Answers

2
votes
$ cat tst.awk
{ buf[NR%6] = $0 }
/ERROR/ { tgt=NR; f=1 }
tgt == NR {
    for (i=1; i<=6; i++) {
        print (NR+i-6) ":", buf[(NR+i)%6]
    }
}
f && /INFO|WARN|DEBUG|TRACE/ { tgt=NR+5; f=0 }

.

$ awk -f tst.awk file
3: DEBUG
4: TRACE
5: TRACE
6: INFO
7: INFO
8: ERROR
9: INFO
10: INFO
11: INFO
12: DEBUG
13: DEBUG
14: DEBUG
0
votes

Try grep and sed

grep -n -A5 -B5 ERROR file.txt | sed 's/:/: /;s/-/: /'
0
votes

I submit this awk for peer reviewing, turned my brain to a bowl of spagetti (can't even spell spaghetti correctly):

$ awk '{
    $0=NR " " $0                     # prepend NR to record
}
!f {
    b[6]=$0                          # buffer to hold 5 previous lines
    for(i=1;i<=5;i++) {
        if(/ERROR/)                  # print previous buffer at ERROR
            print b[i]
        b[i]=b[i+1]
    }
}
/ERROR/,/(INFO|WARN|DEBUG|TRACE)/ {  # between markers arm the output flag
    f=5
}
f&&f--' file                         # keeps negative valued flags out