Mode space and hold space of linux three Musketeers sed

pattern space (pattern space) and hold space (hold space)
(H, h, G, g, x)

pattern space: a temporary buffer for sed processing text content lines, the content in the pattern space will be actively printed to standard output, And automatically clear the pattern space

Keep space: Another temporary buffer for sed processing text content lines, the difference is that the content of the keep space will not be actively emptied, nor will it actively print to standard output, but requires the sed command to process


The relationship between the pattern space and the holding space
Pattern space: equivalent to the pipeline, the text line is processed in the pattern space;
holding space: equivalent to the warehouse, when the data is processed in the pattern space, the data can be temporarily stored in the holding space; as a pattern An auxiliary temporary buffer of space, but independent of each other, can interact, commands can address the mode space but not the hold space. The pattern space can be interacted with using the high-level commands h, H, g, G.

   d      Delete pattern space.  Start next cycle.
          删除pattern space的内容,开始下一个循环

   h H    Copy/append pattern space to hold space.
          复制/追加pattern space的内容到hold space.(复制会覆盖原内容)

   g G    Copy/append hold space to pattern space.
          复制/追加hold space的内容到pattern space.复制会覆盖原内容)

   x      Exchange the contents of the  hold  and  pattern
          spaces.
          交换hold space和pattern space的内容.

The following uses an example to verify the relationship between pattern space and hold space, and to understand the role of advanced commands h, H, g, G

[root@localhost tmp]# cat >> num.txt <<EOF
> One
> Two
> Three
> EOF
[root@localhost tmp]# cat num.txt     
One
Two
Three
[root@localhost tmp]# 
[root@localhost tmp]# tac num.txt 
Three
Two
One
[root@localhost tmp]# 

The command to use sed to output the content of num.txt text in flashback is
as follows:

[root@localhost tmp]# sed '1!G;h;$!d' num.txt 
Three
Two
One
[root@localhost tmp]# 

Note: 1!G: The G command is not executed on the first line
$!d: The d command is not executed on the last line, that is, the pattern space line is not deleted

Schematic:

Mode space and hold space of linux three Musketeers sed


Summarize the relationship between pattern space and hold space
Hold space is a buffer for temporarily storing data in pattern space, assisting pattern space in data processing

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325333259&siteId=291194637