The Concept of 'Hold space' and 'Pattern space' in sed

前端 未结 3 1689
南方客
南方客 2020-12-07 08:39

I\'m confused by the two concepts in sed: hold space and pattern space. Can someone help explain them?

Here\'s a snippet of the manual:

         


        
3条回答
  •  暖寄归人
    2020-12-07 09:16

    @Ed Morton: I disagree with you here. I found sed very useful and simple (once you grok the concept of the pattern and hold buffers) to come up with an elegant way to do multiline grepping.

    For example, let's take a text file that has hostnames and some information about each host, with lots of junk in between that I dont care about.

    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
    

    To me, an awk script to just get the lines with the hostname and the corresponding info line would take a bit more than what I'm able to do with sed:

    sed -n '/Host:/{h}; /Info/{x;p;x;p;}' myfile.txt
    

    output looks like:

    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:

    1. -n disables output unless explicitly printed
    2. first match, finds and puts the Host: line into hold buffer (h)
    3. second match, finds the next Info: line, but first exchanges (x) current line in pattern buffer with hold buffer, and prints (p) the Host: line, then re-exchanges (x) and prints (p) the Info: line.

    Yes, this is a simplistic example, but I suspect this is a common issue that was quickly dealt with by a simple sed one-liner. For much more complex tasks, such as ones in which you cannot rely on a given, predictable sequence, awk may be better suited.

提交回复
热议问题