sed holding space

BUT

Third, keep the space

  • h / H hold, the contents of the pattern space covering h (additional H) into the holding space
  • G / g get, covering the content holding space G (append G) to the pattern space
  • x exchange, swap the contents of two spaces
  • For example
  • The multi-line use, splicing in a row
[root@localhost tmp]#sed 'H;${x;s/\n/,/g;s/^,//};$!d' test

Here Insert Picture Description

  • The line inversion output
[root@localhost tmp]#sed '1!G;h;$!d' test22  
[root@localhost tmp]#sed -n '1!G;h;$p' test22

Here Insert Picture Description

understanding

Here Insert Picture Description

Fourth, change the flow

  • Sed to change the default workflow (script execution from start to finish)

branch
unconditional jump
usage
[address] B [label]
label definitions
: LABEL

For example
test0311 file contents

This is the 0 header line.
This is the 100 first data line.
This is the 200 second data line.
This is the 300 last data line.

Unconditional jump

[root@localhost tmp]#sed '2,3b;s/This is/Is this/;s/line./test?/' test0311

Unconditional jump tagged

[root@localhost tmp]#sed '/first/b jump1;s/This is/Is this/;:jump1;s/line./test?/' test0311

Here Insert Picture Description

Conditional jump

[root@localhost tmp]#echo "This, is , a, test, to, remove, coomas."  | sed ':start;s/,//;t start'

Here Insert Picture Description

  • test
    conditional jump to the specified label

Fifth, an alternative mode

  • &
    & Replace with regular matches to content

example

[root@localhost tmp]#sed  -r 's/[0-9]+/&s/g' test0311

Here Insert Picture Description

  • \ 1 (backward reference)

example

[root@localhost tmp]#sed  -r 's/(^.*)(\b[0-9]+\b )(.*$)/\2\1\3/g' test0311

Here Insert Picture Description

[root@localhost tmp]#echo "abc 123 def" | sed  -r 's/(^.*)(\b[0-9]+ \b)(.*$)/\2\1\3/g' 
123 abc def

Six, sed N line of the two lines of data as processed

1. deleted from the string line breaks, resulting in two lines combined into one line

[root@localhost tmp]#sed '/first/{ N; s/\n/ /}' test

Here Insert Picture Description

2. Replace character

[root@localhost tmp]#sed 'N ; s/this is/Is this/ ' test 

Here Insert Picture Description

Published 147 original articles · won praise 27 · views 8444

Guess you like

Origin blog.csdn.net/weixin_46108954/article/details/104806320
sed