3 .Sed Loop

12 篇文章 0 订阅

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值