Home > Article > System Tutorial > Comprehensive summary: Detailed explanation of Linux sed multi-line processing
Under normal circumstances, sed reads the line to be processed into the pattern space, and the commands in the script process the line one after another until the script is executed, and then the line is output, leaving the pattern space empty; Then repeat the previous action, and a new line in the file is read until the file is processed completely. However, various reasons, such as the user wanting a certain command in the script to be executed under certain conditions, or wanting the pattern space to be retained for next processing, may cause sed to not follow the instructions when processing files. Carry out the normal process. At this time, sed has set up some advanced commands to meet user requirements. If you want to learn the advanced commands of sed, you must first understand the following two buffer areas:
1. Definition of pattern space: Pattern space is a buffer area that saves what sed has just read from the input end.
2. Definition of hold space: Hold space is used to temporarily cache data when processing pattern space data.
There are also several command parameters:
g: Copy the contents of the hold space to the pattern space, and clear the contents of the original pattern space
G: Append the content in the hold space to the pattern space\n
h: Copy the contents of the pattern space to the hold space, and the contents of the original hold space are cleared
H: Append the content in pattern space to hold space\n
x: Exchange the contents of pattern space and hold space
For example, if we want to reverse the contents of a file, the file is as follows:
[qiu.li@l-tdata1.tkt.cn6 ~]$ cat tmp 1-line 2-line 3-line
Execute the following command:
[qiu.li@l-tdata1.tkt.cn6 ~]$ sed '2,$G;h;$!d' tmp 3-line 2-line 1-line
Let’s gradually understand the above execution process
1. Let us analyze the following three commands:
2. Specific operations
Of course, the command: sed '1!G;h;$!d' tmp can also have this effect.
The above is the detailed content of Comprehensive summary: Detailed explanation of Linux sed multi-line processing. For more information, please follow other related articles on the PHP Chinese website!