命令:
d: 删除模式空间中的行;
=:显示行号;
a \text:附加text
i \text:插入text,支持\n实现多行插入;
c \text:用text替换匹配到的行;
p: 打印模式空间中的行;
s/regexp/replacement/:替换由regexp所匹配到的内容为replacement;
g: 全局替换;
w /path/to/somefile:把指定的内容另存至/path/to/somefile路径所指定的文件中;
r /path/from/somefile:在文件的指定位置插入另一个文件的所有内容,完成文件合并
2. 删除/etc/fstab文件中所有以#开头,后跟至少一个空白字符的行的行首的#和空白字符
[root@localhost ~]# sed 's/^#[[:space:]]\+//' /etc/fstab
#
/etc/fstab
Created by anaconda on Wed Aug 26 23:57:24 2015
#
Accessible filesystems, by reference, are maintained under '/dev/disk'
See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/VolGroup-lv_root / ext4 defaults 1 1
UUID=ccfe9f33-b5da-48b1-821b-b3bec206147b /boot ext4 defaults 1 2
/dev/mapper/VolGroup-lv_swap swap swap defaults 0 0
tmpfs /dev/shm tmpfs defaults 0 0
devpts /dev/pts devpts gid=5,mode=620 0 0
sysfs /sys sysfs defaults 0 0
proc /proc proc defaults 0 0
3. 只查看/etc/fstab文件的第1行到第5行
[root@localhost ~]# sed -n '1,5p' /etc/fstab
#
# /etc/fstab
# Created by anaconda on Wed Aug 26 23:57:24 2015
#
4.删除文件中包含“my”的行到包含“you”的行之间的行
[root@localhost ~]# cat file
this is my test line
how are you
hello
how are you tom
my
aaaaaaaaaaaaa
you
[root@localhost ~]# sed '/my/,/you/d' file
hello
how are you tom
5.查询包含“you”的所有行
[root@localhost ~]# sed -n '/you/p' file
how are you
how are you tom
you
6.在文件中每行后面添加空行
[root@localhost ~]# sed 'G' file
this is my test line
how are you
hello
how are you tom
my
aaaaaaaaaaaaa
you
7. 保证指定的文件每一行后方有且只有一个空白行
[root@localhost ~]# sed '/^$/d;G' file
this is my test line
how are you
hello
how are you tom
my
aaaaaaaaaaaaa
you
8.打印奇数行
[root@localhost ~]# sed -n '1~2p' file
1,this is my test line
3,hello
5,my
7,you