3 .Sed Loop

LOOP 类似于goto

we can define a label as follows:

:label 
:start 
:end 
:up

In the above example, a name after colon(:) implies the label name.

:label的形式就是一个label

To jump to a specific label, we can use the b command followed by the label name.

If the label name is omitted, then the SED jumps to the end of the SED file.

[jerry]$ sed -n ' 
h;n;H;x 
s/\n/, / 
/Paulo/!b Print  #这个表示没有找到/Paulo/! 的时候 跳转到:Print
s/^/- / 
:Print 
p' books.txt

demo

[jerry]$ sed -n 'h;n;H;x;s/\n/, /;/Paulo/!b Print; s/^/- /; :Print;p' books.txt

Branches can be created using the t command. The t command jumps to the label only if the previous substitute command was successful.

[jerry]$ sed -n ' 
h;n;H;x 
s/\n/, / 
:Loop 
/Paulo/s/^/-/ 
/----/!t Loop # 如果
p' books.txt 

b 和 t 的差距 查看链接 https://www.thegeekstuff.com/2009/12/unix-sed-tutorial-6-examples-for-sed-branching-operation/

b是无条件挑 t 是有条件跳

b label – jumps to the label with out checking any conditions. If label is not specified, then jumps to the end of the script.

t label – jumps to the label only if the last substitute command modified the pattern space. If label is not specified, then jumps to the end of the script.

demo 去除html 的所有的标签

$ sed '/</{
:loop
s/<[^<]*>//g
/</{
N
b loop
}
}' index.html

demo

$ sed '
:loop
/\\$/N
s/\\\n */ /
t loop' thegeekstuff.txt

Check if the line ends with the backslash (/\$/), if yes, read and append the next line to pattern space, and substitute the \ at the end of the line and number of spaces followed by that, with the single space.
If the substitution is success repeat the above step. The branch will be executed only if substitution is success.
Conditional branch mostly used for recursive patterns.

sed '
:loop
s/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/
t loop'
12342342342343434
12,342,342,342,343,434

更加准确的解释参考

https://www.gnu.org/software/sed/manual/html_node/Branching-and-flow-control.html

b

branch unconditionally (that is: always jump to a label, skipping or repeating other commands, without restarting a new cycle). Combined with an address, the branch can be conditionally executed on matched lines.

t

branch conditionally (that is: jump to a label) only if a s/// command has succeeded since the last input line was read or another conditional branch was taken.

猜你喜欢

转载自blog.csdn.net/successdd/article/details/79078046
sed
今日推荐