So say I find a match with grep -e and I want to print all the lines from the match back to another match, like ---- for instance.

Is that possible, or do I have to use another command like awk or something to do that?

Like for instance, if I have the following file:

Ticket Number: 5465415312

Software Services

My Notepad won't type text.

The output should be like:

Ticket Number: 5465415312

Software Services

And it matches again up back to ---- from Software Services

  • Please proof read. This question is very unclear, and lacks grammar. As such and answers would be guesses at what you want. – ctrl-alt-delor Nov 23 '18 at 23:40
  • What if there is no previous ---? – Jeff Schaller Nov 24 '18 at 0:08
  • @JeffSchaller I'll put one at the top. – leeand00 Nov 24 '18 at 0:30
  • Awk is probably a better tool for what you want. Hard to tell from what you posted and if your file is or is not of uniform syntax – Panther Nov 24 '18 at 0:38
sed -n '/----/,/Software Services/{p;/Software Services/q}' file


Ticket Number: 5465415312

Software Services
| improve this answer | |
  • Nice use of sed, but the op is asking to print lines before or after matching a (single) pattern (I am not sure exactly) not matching multiple patterns or print lines between two patterns (a job for awk IMO). – Panther Nov 24 '18 at 2:38
  • @Panther This is the sed way of doing it. The question implicitly talks about two patterns. One pattern to trigger output and another to delimit from where the output should start. – Kusalananda Feb 3 '19 at 19:58

Using awk, the short way of doing it:

awk '/^----$/,/^Software Services$/' file

The long and roundabout way of doing it:

awk '/^----$/              { lines = "" }
                           { lines = (lines == "" ? $0 : lines ORS $0) }
     /^Software Services$/ { print lines }' file

That is, empty the string saved in lines every time we hit a line of four dashes. Then always append the current line to lines, and print the contents of lines when we find the "trigger" line in the input data.

| improve this answer | |

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.