您的位置:首页 > 运维架构 > Shell

shell笔记之sed编辑器的基础用法(完结)

2012-05-29 10:36 489 查看
接上篇:

一、变换命令.

变换命令(y)仅针对单个字符进行操作变换,变换命令格式如下:

[address]y/inchars/outchars/

变换命令采用一对一的字符模式,就是将inchars的第一个字符变换成outchars的第一个字符,inchars的第二个字符变成outchars第二个字符,依次类推。注意一点,inchars和outchars的变换字符长度必须相等,否则,sed编辑器执行命令时会报错的。

看如下示例:

$ cat test2.txt
this is script test, we are test bash shell 1
this is script test, we are test bash shell 2
this is script test, we are test bash shell 3
this is script test, we are test bash shell 4
this is script test, we are test bash shell 5

$ sed 'y/123/789/' test2.txt
this is script test, we are test bash shell 7
this is script test, we are test bash shell 8
this is script test, we are test bash shell 9
this is script test, we are test bash shell 4
this is script test, we are test bash shell 5

上面直接将1,2,3数字变成了7,8,9 长度是相等的!

变换命令是全局命令,也就是说它会对文本行中出现的任意字符进行替换,而不能针对特定字符进行替换。示例:

$ echo "this 1 is a test 1 line" | sed 'y/123/456/'
this 4 is a test 4 line

echo输出行中出现两个数字1,使用(s)替换命令,一般都替换行首第一个匹配字符,但是变换命令(y)却将输出行的任何匹配字符都变换成匹配字符串了。这就是变换命令(y)不同于其他命令之处!

二、打印命令

小写p命令用于打印文本行
(=)命令用于打印行号
小写l用于列出行命令

下面看第一个示例:

$ echo "this is a test"|sed 'p'
this is a test
this is a test

上例第二行就是使用(p)命令打印出来的。

接下来再看只打印与文本模式匹配的行:

$ sed -n '/number 3/p' test2.txt
this is script test, we are test bash shell 3

加上-n参数,打印一段行范围:

$  sed -n '2,3p' test2.txt
this is script test, we are test bash shell 2
this is script test, we are test bash shell 3

如果要在更改行之前显示改行,继续看下面示例:

$ sed -n '/3/{
p
s/test/line/p
}' test2.txt
this is script test, we are test bash shell 3
this is script line, we are test bash shell 3

(=)号可以打印出当前输出行号,如果利用sed命令处理文本过程中想打印行号,就加(=)号吧:

$ sed '=' test2.txt
1
this is script test, we are test bash shell 1
2
this is script test, we are test bash shell 2
3
this is script test, we are test bash shell 3
4
this is script test, we are test bash shell 4
5
this is script test, we are test bash shell 5

$ sed -n '/number 4/{
> =
> p
> }' test2.txt
4
this is script test, we are test bash shell 4

列出行l允许打印数据流中的文本和不可打印的ASCII字符,示例如下:

$ sed -n 'l' test2.txt
this is script test, we are test bash shell 1$
this is script test, we are test bash shell 2$
this is script test, we are test bash shell 3$
this is script test, we are test bash shell 4$
this is script test, we are test bash shell 5$

不可打印的特殊字符,也显示出来了。

三、将文件用于sed

1、写文件

w命令用作将文本行写入文件。格式如下:

[address]w filename

filename可以是相对路径或者绝对路径,但是使用sed编辑器执行命令的用户必须对文件具有写权限。另外,寻址模式不限,单行、文本模式或行号或文本模式范围:

$ sed '1,2w newtest' test2.txt
this is script test, we are test bash shell 1
this is script test, we are test bash shell 2
this is script test, we are test bash shell 3
this is script test, we are test bash shell 4
this is script test, we are test bash shell 5

$ cat newtest
this is script test, we are test bash shell 1
this is script test, we are test bash shell 2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  基础 编辑器