@ Ed Morton: I do not agree with you here. I found that sed very useful and simple (when you understand the concept of a pattern and hold down buffers) to come up with an elegant way to do multi-line searches.
For example, let's take a text file that contains host names and some information about each host, with a lot of garbage in between, which does not bother me.
Host: foo1 some junk, doesnt matter some junk, doesnt matter Info: about foo1 that I really care about!! some junk, doesnt matter some junk, doesnt matter Info: a second line about foo1 that I really care about!! some junk, doesnt matter some junk, doesnt matter Host: foo2 some junk, doesnt matter Info: about foo2 that I really care about!! some junk, doesnt matter some junk, doesnt matter
For me, the awk script to get the strings with the host name and the corresponding info string would take a little more than what I can do with sed:
sed -n '/Host:/{h}; /Info/{x;p;x;p;}' myfile.txt
the output looks like this:
Host: foo1 Info: about foo1 that I really care about!! Host: foo1 Info: a second line about foo1 that I really care about!! Host: foo2 Info: about foo2 that I really care about!!
(Note that Host: foo1 appears twice in the output.)
Explanation:
-n disable output if not explicitly printed- first match, finds and places the string
Host: in the hold buffer (h) - in the second match, it finds the following line Info: but first exchanges (x) the current line in the template buffer with a hold buffer, and prints (p) the line
Host: then repeatedly exchanges (x) and prints (p) Info: the line.
Yes, this is a simplified example, but I suspect that this is a common problem that a simple single-line sed quickly dealt with. For much more complex tasks, such as tasks in which you cannot rely on a given, predictable sequence, awk might be better.
Jens Jensen Aug 19 '13 at 19:30 2013-08-19 19:30
source share