LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   GAWK Find Pattern Print Lines Before and After (https://www.linuxquestions.org/questions/programming-9/gawk-find-pattern-print-lines-before-and-after-4175482955/)

metallica1973 10-31-2013 03:36 PM

GAWK Find Pattern Print Lines Before and After
 
Using grep I can easily use:

Code:

cvs log |grep -iB 10 -A 10 'date: 2013-10-30'
to display search results and 10 lines before and after. How can this be accompished using gawk?

Firerat 10-31-2013 06:22 PM

I can't really see why you would want to do it with awk, but
  • if countdown greater than 0
    • print $0
    • subtract 1 from countdown
    • next record
  • if pattern exists
    • print all elements in array
    • print $0
    • unset array
    • start countdown at 10
    • next record
  • if pattern not exist
    • if No of elements in array = 10
      • for element in 1 to 9,
        • array[element-1]=array[element];
      • array[9]="$0"
      • next record
    • add $0 to array
    • next record


^^ untested ( as well as unwritten as awk )
it can be done, but I don't know why since grep -C10 will do the same with less effort

NOTE:, there is probably a much better way of doing it in awk than my above 'logic'

danielbmartin 10-31-2013 10:38 PM

Quote:

Originally Posted by metallica1973 (Post 5056097)
Using grep I can easily use:

Code:

cvs log |grep -iB 10 -A 10 'date: 2013-10-30'
to display search results and 10 lines before and after. How can this be accomplished using gawk?

I changed the 10-line context to 3 lines for ease of testing.

With this InFile ...
Code:

line 01
date: 2013-10-30
line 03
line 04
line 05
line 06
line 07
line 09
line 10
line 11
date: 2013-10-30
line 13
line 14
line 15
line 16
line 17
line 18
line 19
date: 2013-10-30
line 21
line 22
line 23
date: 2013-10-30
line 25
date: 2013-10-30
line 27
line 28
line 29
line 30
line 31
line 32
line 33
date: 2013-10-30

... this gawk ...
Code:

gawk '{l[NR]=$0; if ($0~"date: 2013-10-30") {for (j=NR-3;j<=NR+2;j++) {a[j]=1}; a[j]=a[j]+99}}
  END{for (j=1;j<=NR;j++) {if (a[j]) print l[j]; if (a[j]>9) print "---" }}' $InFile >$OutFile

... produced this OutFile ...
Code:

line 01
date: 2013-10-30
line 03
line 04
line 05
---
line 09
line 10
line 11
date: 2013-10-30
line 13
line 14
line 15
---
line 17
line 18
line 19
date: 2013-10-30
line 21
line 22
line 23
date: 2013-10-30
line 25
date: 2013-10-30
line 27
line 28
line 29
---
line 31
line 32
line 33
date: 2013-10-30

Daniel B. Martin

metallica1973 11-07-2013 09:12 PM

thanks for the reply. You have left me speechless on how long it would take to use gawk instead of simply using grep.


All times are GMT -5. The time now is 02:54 AM.