sed高级编程(二)
- 否定命令:!用于否定命令。
创建反转行sed编辑器脚本:(tac在Linux中也可以执行反转文本文件的功能)
sed -n '{ > 1!G > h > $p > }' filename
sed分支命令:
[address]b [label]
address决定激发分支命令。如果label参数不存在,则分支命令将继续执行到脚本的结尾。$cat data This is the header line. This is the first data line. This is the second data line. This is the last line. sed '{ > 2,3b > s/This is/Is this/ > s/line./test? > } ' data Is this the header test? This is the first data line. This is the second data line. Is this the last test? # 分支命令跳过数据流中的第二行和第三行的替换命令。
除了到达脚本的最后,还可以定义一个想要分支命令转到的标签。标签以冒号开头,最长为7个字符:
:label2
要指定标签,只需要将它添加到b命令的后面。使用标签可以跳过与分支地址匹配的命令,而仍然执行脚本中的其他命令:$cat data This is the header line. This is the first data line. This is the second data line. This is the last line. sed '{ > /first/b jump1 > s/is/might be/ > s/line/test > :jump1 > s/data/text > } ' data This might be the header test This is the first text line. This might be the second text test. This might be the last test. # 分支命令指示,如果行中出现匹配文本first,则程序应该跳刀脚本中以jump1标记的行。如果分支命令模式不匹配,则sed编辑器继续执行脚本中的命令,包括分支标签之后的命令。(也就是说,在不匹配分支模式的行上继续窒息ing所有3个替换命令)。如果行匹配分支模式,则sed编辑器分支到分支标签行。因此,只执行最后一个替换命令。
sed脚本分支命令还可以出现在脚本前面的标签:
$echo "This, is, a, test, to, remove, commas." | sed -n '{
> :start
> s/,//lp
> /,/b start
> }'
测试:测试命令(t)用于更改sed编辑器脚本的流程。测试命令不是基于地址跳转到标签,而是基于替换命令的结果专挑到标签。如果替换命令成功匹配并替换一个模式,则测试命令分支到指定的标签。如果替换命令不匹配指定的模式,则测试命令不分支:
[adderss]t [label]
$cat data This is the header line. This is the first data line. This is the second data line. This is the last line. sed ' { > s/first/starting/ > t > s/line/test > }' data This is the header test. This is the starting data line This is the second data test. This is te last test. #第一个替换命令查找模式文本first。如果行上能够匹配模式,则替换该文本,而测试命令跳过后续的替换命令。如果第一个命令未能匹配 ,则执行第二个替换命令
模式替换:与号(&)用于表示替换命令中额匹配模式。:
(1) $echo "The cat sleeps in his hat." | sed 's/.at/".at"/g ' The ".at" sleeps in his ".at". (2) $echo "The cat sleeps in his hat." | sed 's/.at/"&"/g' The "cat" sleeps in his "hat".
sed编辑器使用圆括号定义替换模式中的子字符串元素。然后在替换模式中使用特定的符号来引用子字符串元素。替换字符由反斜杠和数字组成。数字表示子字符串元素的位置。sed将第一个元素分配为字符\1,第二个元素分配成字符\2,类推。(圆括号必须使用转义字符来表示它们是分组字符。):
(1) $echo "The System Administrator manual" | sed ' > s/\(System\) Administrator/\1 User/' The System User manual (2) $echo "That furry cat is pretty" | sed 's/furry \(.at\)/\1/' That cat is pretty. $echo "That furry hat is pretty" | sed 's/furry \(.at\)/\1/' That hat is pertty. (3) $echo "1234567" | sed '{ > :start > s/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/ > t start > }' 1,234,567 #脚本在测试中递归,直至放置号所有的逗号。