本文内容较简洁,适合linux有点基础的菜鸟。。。

功能介绍之后都有例子便于理解,希望对大家能起到帮助作用


sed 是一种在线编辑器,它一次处理一行内容。处理时,把当前处理的行存储在临时缓冲区中,称为“模式空间”(pattern space),接着用sed命令处理缓冲区中的内容,处理完成后,把缓冲区的内容送往屏幕。接着处理下一行,这样不断重复,直到文件末尾。文件内容并没有 改变,除非你使用重定向存储输出。Sed主要用来自动编辑一个或多个文件;简化对文件的反复操作;编写转换程序等


1、num1num2:操作从num1行到num2行的内容,若只有一个num,则为精确匹配该行

EG[root@server1 mnt]# sed '13d' test 删除文件的13

2word1word2:从第一次匹配到字符word1到第一次匹配到字符word2之间的所有行

3m +n:从m行开始后面的n

EG[root@server1 mnt]# sed '1 +3d' test 删除文件的第1行和后面的3

4num a  \word :在num行后年添加字符word

5num i   \word :在num行前面添加字符word

EG:

[root@server1 mnt]# sed '2a \hello' test

 

hello, like

hello

hello, love

[root@server1 mnt]# sed '2i \hello' test

 

hello

hello, like

hello, love

若想再添加一行则:

[root@server1 mnt]# sed '2a \hello\n\world' test \n为换行符)

 

hello, like

hello

world

hello, love

6r FILE:在指定行后面添加FILE内的内容

EG: sed '2r /etc/passwd' fstab ##在第二行后面加上/etc/passwd文件的内容

7w FILE:将地址指定范围内的内容另存到FILE

EG:

[root@server1 mnt]# sed -n '1,3w /mnt/test1' /etc/passwd

[root@server1 mnt]# cat test1

root:x:0:0:root:/root:/bin/bash

bin:x:1:1:bin:/bin:/sbin/nologin

daemon:x:2:2:daemon:/sbin:/sbin/nologin

 

8&***:在匹配到的内容后面加上***

9l***:在匹配到的内容后面减去*** (小写L

EG

[root@server1 mnt]# cat test

 

hello, like

hello, love

[root@server1 mnt]# sed  's/l..e/&r/'  test

 

hello, liker

hello, lover

[root@server1 mnt]# sed  's/l..r/lr/' test

 

hello, like

hello, love

 

Sed功能选项:

-n:只显示被匹配到的内容,不在显示模式空间内的内容

-i:对源文件更改 

 

sed+正则表达式的扩展:

##测试文件为test

1、删除文件的空白行: sed '/^$/d' test

2、删除文件中行首的空白符: sed 's/^[[:space:]]//' test

3、删除文件中开头的#,但#后面必须有空白:sed 's/^#[[:space:]]//' test