Get matching pairs from text file
I have a text file test1.txt:
1 first_match
2 not_needed_line1
3 not_needed_line2
4 not_needed_line3
5 second_match
6 not_needed_line4
7 not_needed_line5
8 not_needed_line6
9 not_needed_line7
10 not_needed_line8
11 first_match
12 second_match
13 not_needed_line9
14 not_needed_line10
15 not_needed_line11
16 second_match
17 not_needed_line12
18 not_needed_line13
19 second_match
20 not_needed_line14
21 second_match
22 not_needed_line15
23 not_needed_line16
24 first_match
25 not_needed_line17
26 not_needed_line18
27 second_match
I would like to extract pairs containing "first_match" and "second_match" and add filename test1.txt before each line in result.
In this example it will be lines:
#1 and #5
#11 and #12
#24 and #27
Please note - lines #16, #19 and #21 are not included, because they are missing first matching line from pair "first_match".
I found awk (GNU Awk 3.1.6) script to extract all lines between pairs.
/first_match/{printf FILENAME " - "; f=1} f; /second_match/{f=0}
Result is:
test1.txt - 1 first_match
2 not_needed_line1
3 not_needed_line2
4 not_needed_line3
5 second_match
test1.txt - 11 first_match
12 second_match
test1.txt - 24 first_match
25 not_needed_line17
26 not_needed_line18
27 second_match
Questions:
- How to get only pairs containing "first_match" and "second_match"?
test1.txt - 1 first_match
test1.txt - 5 second_match
test1.txt - 11 first_match
test1.txt - 12 second_match
test1.txt - 24 first_match
test1.txt - 27 second_match
- How to get only second line from pair - "second_match"?
test1.txt - 5 second_match
test1.txt - 12 second_match
test1.txt - 27 second_match
from Recent Questions - Stack Overflow https://ift.tt/3pJV6uE
https://ift.tt/eA8V8J
Comments
Post a Comment