Chinaunix首页 | 论坛 | 博客
  • 博客访问: 23860
  • 博文数量: 2
  • 博客积分: 1227
  • 博客等级: 少尉
  • 技术积分: 30
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-24 08:45
文章分类

全部博文(2)

文章存档

2010年(2)

分类:

2010-03-03 21:14:12

      最近学习sed,发现各种书上对于标签讲的很少,所以写了篇文章,说说我的理解。
      关于sed标签,在manpage中是这样说的:
 b label
              Branch to label; if label is omitted, branch to end of script.
 t label
              If a s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if  label
              is omitted, branch to end of script.
 T label
              If no s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label
              is omitted, branch to end of script.
      标签在sed当中的作用就是跳转。从manpage可以得知,t lable和T lable的作用是相反的,那么我们主要来看看b lable和t lable。接下来实例说明,首先,创造个文件:
[root@A ~]# cat b
The colour is red
The colour is green
The colour is black
The colour is yellow
      执行以下语句:
[root@A ~]# sed '{/colour/b lable;s/colour/COLOUR/;:lable; s/$/ \!/}' b
The colour is red !
The colour is green !
The colour is black !
The colour is yellow !
      我们看到,执行了sed命令后在文件的每一行后面加上了“!”,而并没有将“colour”替换成为“COLOUR”。可以看到,我们定义了一个标签lable(:lable),那么这条语句的作用就是如果匹配到了colour(/colour/),那么就跳转到标签lable处继续执行下面的命令(s/$/ \!/),而略过了(s/colour/COLOUR/),这就是b lable的作用。接着看:
      执行以下语句(这是sed1line中的一个例子):

[root@A ~]# sed '{:a;s/^.\{1,78\}$/ &/;ta}' b
                                                              The colour is red
                                                            The colour is green
                                                            The colour is black
                                                           The colour is yellow
      可以看出,语句执行后,文件中的每一行都占用了79个字符并且右对齐了,那么sed语句是怎么得到这个结果的呢?首先,设置了一个标签(:a),接下来执行s/^.\{1,78\}$/ &/,它的作用是在每一行原本内容的前面补一个空格,如果执行成功,那么就继续执行ta,ta是什么意思?这就是我们要说的条件跳转,只有当它前面的替换成功了,才会执行ta,如果前面的替换不成功,那么sed对这一行的处理就over了,该下一行了,就这么简单。在这个例子中,实际上:a.....ta形成了一个循环,它不停的执行替换,直到这一行的字符数量达到了78加上一个空格共79个的时候,那么循环停止,也就是替换不成功了,那么就不会再执行ta了,sed会接着开始处理下一行。

      sed我也是初学,关于标签的更多用法,我也在研究当中,这次就先说这么多了!

 

阅读(4151) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:字符串截取的利器---${varname: n1:n2}

给主人留下些什么吧!~~