سؤال

sed '/Storage/,/Design/p' sample.txt

The above helps to print the lines between Storage and Design.

My question is how to get the second occurrence of the above sed command ?

My file has many Storage - Design pattern matches, but I want to take second occurrence paragraph.

هل كانت مفيدة؟

المحلول

This awk prints second section:

cat file
start
1 data
end
not this
start
2 more data
end
not here

awk '/start/ {f=1;a++} f && a==2; /end/ {f=0}' file
start
2 more data
end

It the file has more start than end this counts group of start/end

cat file
start
start
1 data
end
not this
start
2 more data
end
not here

awk '/start/ {f=1} f && a==1; /end/ {if (f) a++;f=0}' file
start
2 more data
end

نصائح أخرى

Perl solution:

perl -ne '$count++ if /start/; print if /start/ .. /end/ and 2 == $count'
sed -n '/Storage/,/Design/ H
/Design/ {
    g
    s/\(.*Storage\)\{2\}/Storage/
    t print
    b
 : print
    p
    q
    }' YourFile

Keep all Storage section in buffer, when buffer is feeded with 2 Storage, remove first, print section and quit. I use the \{2\} to easily change the selected occurence (sed limitation is 255 if i remeber well but is easy to workaround)

This might work for you (GNU sed):

sed -n '/Storage/,/Design/{x;/./{x;p;x};x;/Design/h}' file

As @jotne has pointed out to cease after the second occurence:

sed -n '/Storage/,/Design/{x;/./{x;p;/Design/q;x};x;/Design/h}' file
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top