How to display x lines before a record and x lines after a find record when we have two of the same string

Viewed 30

How to display, for example, 10 lines before a found record and 10 lines after a found record when we have two of the same string in one file ? See file example (RECORD in line 10 is our search):

<Test1>  </Test1>
<Test2>  </Test2>
<Test3>  </Test3>
<Test4>  </Test4>
<Test5>  </Test5>
<Test6>  </Test6>
<Test7>  </Test7>
<Test8>  </Test8>
<Test9>  </Test9>
<Test10> **RECORD** </Test10>
<Test11>  </Test11>
<Test12>  </Test12>
<Test13>  </Test13>
<Test14>  </Test14>
<Test15> RECORD </Test15>
<Test16>  </Test16>
<Test17>  </Test17>
<Test18>  </Test18>
<Test19>  </Test19>
<Test20>  </Test20>

I tried something like this:

grep -m 1 -B 10 -A 10 RECORD *

but this only works until the next record met (lines from 1 to 14) and I would like to find all the lines I am looking for.

I expect such a result (aims for the result for the first value):

<Test1>  </Test1>
<Test2>  </Test2>
<Test3>  </Test3>
<Test4>  </Test4>
<Test5>  </Test5>
<Test6>  </Test6>
<Test7>  </Test7>
<Test8>  </Test8>
<Test9>  </Test9>
<Test10> **RECORD** </Test10>
<Test11>  </Test11>
<Test12>  </Test12>
<Test13>  </Test13>
<Test14>  </Test14>
<Test15> RECORD </Test15>
<Test16>  </Test16>
<Test17>  </Test17>
<Test18>  </Test18>
<Test19>  </Test19>
<Test20>  </Test20>
1 Answers

With your shown samples and attempts, please try following awk code. As per your shown samples I have neglected null values in xml file. Reading the Input_file 2 times here in awk program.

awk -F"[><]" '
FNR==NR{
  if($3){ arr1[$3]++ }
  arr2[FNR]=$0
  next
}
$3!~/^[[:space:]]++$/ && arr1[$3]>1 && !($3 in arr3){
  for(i=(FNR-10);i<=FNR;i++){
    if(arr2[i]){ print arr2[i] }
  }
  for(i=(FNR+1);i<=(FNR+10);i++){
    print arr2[i]
  }
  arr3[$3]
}
'  Input_file  Input_file

NOTE: This will look for all those strings who are having more than 1 occurrences in Input_file and it will print 10 above and 10 below lines from 1st occurrence itself as per shown samples but it will do this operation for all eligible/found strings.

Related