2

I want to print output between two pattern and first pattern should be second time matching in file.

Example -

test.txt

start one
text_1   
end
start two
text_2
end 
start three
text_3
end

Here first pattern is start and second pattern is end. Pattern start should be second time pattern matching in file. Then output should be

start two
text_2
end
  • If the file format is always the same you could simply use sed -n '4,/end/p' filename – Valentin Bajrami Mar 3 '17 at 9:12
2

With awk, easily extensible to any nth record:

awk '/start/ && ++n == 2, /end/' < file

would print the lines from the second occurrence of start to the first occurrence of end after that.

To print the second start to end record (would make a difference if there are start,start,end sequences):

awk '
  /start/, /end/ {
    if (!seen) {seen = 1; n++}
    if (n == 2) print
    if (/end/) seen = 0
  }' < file

Or:

awk '
  !inside && /start/ {inside = 1; n++}
  !inside {next}
  n == 2
  /end/ {inside = 0}' < file 
1

With sed

sed -n '/start/,/end/n;/start/,/end/{p;/end/q}' file

Explanation:

  • -n supresses output
  • first /start/,/end/n extract first start-to-end block, but do nothing (via n)
  • then for the second start-to-end block /start/,/end/ print and quit as soon as end is reached p;/end/q
0

In this particular case - when the input consists only of /start/,/end/ blocks you can simply do

sed '1,/end/d;//q' infile

If there are other lines between those blocks (not matching end) then

sed '1,/end/d;/start/,/end/!d;/end/q' infile

For the more general case when the block to be extracted is the nth one you could run:

n=5
awk  -vc=$n '/start/{i++};{if (i==c){print;if (/end/){exit}}}' infile
0
sed -ne '
   /^start/,/^end/!d; # skip non-interesting block
   /^start/H;         # increment hold counter
   G;/\n.*\n.*\n/!d;  # check if 2nd block reached?
   P;/^end/q;         # we"re in 2nd block so print & quit on /end/
' yourfile

perl -l -0777ne 'print+(/^start.*?\nend[^\n]*$/msg)[1]' yourfile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.