3 .Sed Loop

LOOP is similar to goto

we can define a label as follows:

:label 
:start 
:end 
:up

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

The form of :label is a 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 

The gap between b and t check the link https://www.thegeekstuff.com/2009/12/unix-sed-tutorial-6-examples-for-sed-branching-operation/

b is an unconditional pick t is a conditional jump

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 removes all tags from 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

More accurate explanation reference

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.

Guess you like

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