Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1351363
  • 博文数量: 245
  • 博客积分: 10021
  • 博客等级: 上将
  • 技术积分: 3094
  • 用 户 组: 普通用户
  • 注册时间: 2008-05-12 14:51
文章存档

2011年(2)

2009年(152)

2008年(91)

我的朋友

分类:

2008-05-20 08:54:56

使用替换修改字符串
如果要附加或修改一个字符串,可以使用(&)命令,&命令保存发现模式以便重新调用它,然后把它放在替换字符串里面。
先给出一个被替换模式,然后是一个准备附加在第一个模式后的另一个模式,并且后面带有&,这样修改模式将放在匹配模式之前。
例如, s e d语句s/nurse/"Hello"&/p 的结果如下

CODE:
[sam@chenwy sam]$ sed -n 's/nurse/"hello" &/p' quote.txt
The local "hello" nurse Miss P.Neave was in attendance.

原句是文本行The local nurse Miss P.Neave was in attendance。
记住模式中要使用空格,因为输出结果表明应加入空格。

还有一个例子:

CODE:
[sam@chenwy sam]$ sed -n 's/played/from Hockering &/p' quote.txt
The honeysuckle band from Hockering played all night long for only $90.

原句是The honeysuckle band played all night long for only $90。

将sed结果写入文件命令
像使用>文件重定向发送输出到一个文件一样,在s e d命令中也可以将结果输入文件。格式有点像使用替换命令:

CODE:
[ a d d r e s s [,address]]w filename

‘w’选项通知s e d将结果写入文件。f i l e n a m e是自解释文件名。
下面有两个例子。

CODE:
[sam@chenwy sam]$ sed '1,2 w filedt' quote.txt
The honeysuckle band played all night long for only $90.
It was an evening of splendid music and company.
Too bad the disco floor fell through at 23:00.
The local nurse Miss P.Neave was in attendance.

文件q u o t e . t x t输出到屏幕。模式范围即1,2行输出到文件f i l e d t。

CODE:
[sam@chenwy sam]$ cat filedt
The honeysuckle band played all night long for only $90.
It was an evening of splendid music and company.

下面例子中查询模式N e a v e,匹配结果行写入文件f i l e d h t。

CODE:
[sam@chenwy sam]$ sed '/Neave/ w dht' quote.txt
The honeysuckle band played all night long for only $90.
It was an evening of splendid music and company.
Too bad the disco floor fell through at 23:00.
The local nurse Miss P.Neave was in attendance.



CODE:
[sam@chenwy sam]$ cat dht
The local nurse Miss P.Neave was in attendance.

从文件中读文本
处理文件时, s e d允许从另一个文件中读文本,并将其文本附加在当前文件。此命令放在模式匹配行后,格式为:

CODE:
address r filename

这里r通知s e d将从另一个文件源中读文本。f i l e n a m e是其文件名。

现在创建一个小文件s e d e x . t x t,内容如下:

CODE:
[sam@chenwy sam]$ echo "Boom boom went the music" >sedex.txt
[sam@chenwy sam]$ cat sedex.txt
Boom boom went the music

将s e d e x . t x t内容附加到文件q u o t e . t x t的拷贝。在模式匹配行/ c o m p a n y /后放置附加文本。本例为第三行。注意所读的文件名需要用单引号括起来。

CODE:
[sam@chenwy sam]$ sed '/company./r sedex.txt' quote.txt
The honeysuckle band played all night long for only $90.
It was an evening of splendid music and company.
Boom boom went the music
Too bad the disco floor fell through at 23:00.
The local nurse Miss P.Neave was in attendance.

匹配后退出
有时需要在模式匹配首次出现后退出s e d,以便执行其他处理脚本。退出命令格式为:

CODE:
address q

下面的例子假定查询模式/ . a . * /,意为任意字符后跟字符a,再跟任意字符0次或任意多次。
查询首次出现模式,然后退出。需要将q放在s e d语句末尾。

CODE:
[sam@chenwy sam]$ sed '/.a.*/q' quote.txt
The honeysuckle band played all night long for only $90.
阅读(7702) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~