I would like to print the nth match of a sed search which is based on two patterns, as shown below:
sed -n '/start here/,/end here/p' 'testfile.txt'
Let's say that testfile.txt
contains the text below:
start here
0000000
0000000
end here
start here
123
1234
12345
123456
end here
start here
00000000
end here
00000000
00000000
and that I do not want to print the zeros between the two patterns.
Based on the command above, I will get all the matches between the patterns, and its output is shown below:
start here
0000000
0000000
end here
start here
123
1234
12345
123456
end here
start here
00000000
end here
While my desired output is:
start here
123
1234
12345
123456
end here
Consider that the lines need to be printed as in testfile.txt
and not concatenated.
Best Answer
I would just switch to another tool. Perl, for example:
That will print the 3rd match. Change the
$k==3
to whatever value you want. The logic is:$k++ if /Pattern1/
: increment the value of the variable$k
by one if this line matchesPattern1
.if(/Pattern1/ .. /Pattern2/){print if $k==3}
: if this line is within the range of/Pattern1/
to/Pattern2/
, print it but only if$k
is 3. Change this value to whichever match you want.You could wrap this in a little shell function to be able to get the Nth match more easily:
You could then run it like this:
Using your example data:
Or:
Just for fun, here's another perl approach:
Or, if you like golfing (thanks @simlev):