4

How to get all the lines after a matching word till the next different matching word?

For example, my input looks like below.

1
2
3

5
6

and I need to sed from 1 to 5 and in my output I need to include 1 but I do not want to include *5*and the remaining lines.

If my file contains no 5, I need to do have the remaining lines till the end.

NOTE: I saw the referenced link that looks like a duplicate to my question, titled: Show only text between 2 matching pattern but it doesn't answer my question. The answers there didn't include a way to handle if the secondmatch isn't in the file.

  • Did the dup referenced above look like it would solve your problem? – slm Oct 15 '14 at 13:58
5
sed '/1/,/5/!d;/5/d'

Would return the lines starting from a line containing 1 up to the next line after that that contains 5 (not including that one). If there's no line containing 5 after the one containing 1, it will print from the first line containing 1 to the end of the file.

Note that it will print all the corresponding sections.

If there's only one section, or you're only interested in the first one, another approach could be:

sed -n '/1/,$!d; /5/q; p'

That means sed will stop reading after it has found a 5 on the same line, or after the first line that contains 1.

  • i dont know if it just for me but none of the way works if it cannot find second match. Im using it wget -r --spider http://www.domain.com -o file.txt | sed '/1/,/5/!d;/5/d' file.txt – Benas Gasiūnas Oct 15 '14 at 14:24

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.