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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章