Jonny P
Jonny P

Reputation: 453

How can i grep from one point to another while ignoring the first match?

I want to grep from one string, to the second occurance of another string. Example file:

11111111
22222222
33333333
44444444
55555555
66666666
77777777
88888888
77777777
99999999

For example, my first match is '22222222' second match is second occurance of '77777777' so the output would be:

22222222
33333333
44444444
55555555
66666666
77777777
88888888
77777777

I know i can use sed to get from the first match to the second match like this:

sed -n -e '/22222222/,/77777777/ p'

However i am struggling to make it ignore the first 77777777, i have tried adding 2,$, But it gives me an error. How can i acheive this?

Upvotes: 2

Views: 197

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133518

Could you please try following.

awk '$0==22222222{found1++} $0==77777777{found2++} found1;found2==2{exit}' Input_file

Explanation: Adding detailed explanation for above code.

awk '             ##Starting awk program from here.
$0==22222222{     ##Checking if line is 22222222 then do following.
  found1++        ##Creating variable found1 and keep increasing its value by 1 here.
}                 ##Closing BLOCK for above condition here.
$0==77777777{     ##Checking if line is 77777777 then do following.
  found2++        ##Creating variable found2 and keep increasing its value by 1 here.
}                 ##Closing BLOCK for above condition here.
found1            ##Checking condition if found1 variable is NOT NULL then it will print that line.
found2==2{        ##Checking condition if variable found2 is equal to 2 then do following.
  exit            ##Using exit function of awk to exit from program since 2nd occurrence if found and NO need to read rest of the file.
}
' Input_file      ##Mentioning Input_file name here.
  • Using exit will save our time; why because once 2nd occurrence of 77777777 is found there is no need to read rest of the Input_file then.

Upvotes: 4

Related Questions