sed的使用


sed
-n:表示仅显示处理后的结果
[root@centos ~]# sed -n 'p' aaa //输出所有内容
[root@centos ~]# sed -n '3p' aaa //输出第三行内容
[root@centos ~]# sed -n '3,5p' aaa //输出3-5行内容
[root@centos ~]# sed -n 'p;n' aaa //输出所有奇数行
[root@centos ~]# sed -n 'n;p' aaa //输出所有偶数行
[root@centos ~]# sed -n '3,5{p;n}' aaa //输出3~5行的所有奇数行
[root@centos ~]# sed -n '10,${n;p}' aaa //输出文件10至末行的所有偶数行
[root@centos ~]# sed -n '/the/p' aaa //输出包含the的行
[root@centos ~]# sed -n '4,/the/p' aaa //输出从第四行至第一个包含the的行
[root@centos ~]# sed -n '/the/=' aaa //输出包含the的行所在的行号
[root@centos ~]# sed -n '/^PI/p' aaa //输出以PI开头的行
[root@centos ~]# sed -n '/[0-9]$/p' aaa //输出以数字结尾的行
[root@centos ~]# sed -n '/\删除符合条件的文本(d)
[root@centos ~]# nl aaa | sed '3d' //删除第三行
[root@centos ~]# nl aaa | sed '3,5d' //删除3~5行
[root@centos ~]# sed '/cross/d' aaa //删除包含cross的行
[root@centos ~]# sed '/^[a-z]/d' aaa //删除以小写字母开头的行
[root@centos ~]# sed '/\.$/d' aaa //删除以 . 结尾的行
[root@centos ~]# sed '/^$/d' aaa //删除所有空行
替换符合条件的文本(s)
[root@centos ~]# sed 's/the/THE/' aaa //将每一行中的第一个the替换为THE
[root@centos ~]# sed 's/l/L/3' aaa //将每行中的第3个l替换为L
[root@centos ~]# sed 's/the/THE/g' aaa //将文中所有the替换为THE
[root@centos ~]# sed 's/o/ /g' aaa //将文中所有o删除(替换空格)
[root@centos ~]# sed 's/^/#/g' aaa //在每行行首插入#号
[root@centos ~]# sed '/the/s/^/#/' aaa //在包含the的每行行首插入#号
[root@centos ~]# sed 's/$/EOF/' aaa //在每行行尾插入字符串EOF
[root@centos ~]# sed '3,5s/the/THE/g' aaa //将3~5行中的所有the替换为THE
[root@centos ~]# sed '/the/s/o/0/g' aaa //将包含the的所有行中的o替换成0
迁移符合条件的文本
[root@centos ~]# sed '/the/{H;d};$G' aaa //将包含the的行迁移至文件末尾
[root@centos ~]# sed '1,5{H;d};13G' aaa //将第1~5行迁移至第13行后
[root@centos ~]# sed '/the/a bbb' aaa //将包含the的行另存文件为bbb
[root@centos ~]# sed '/the/r /etc/hostname' aaa //将文件/etc/hostname 的内容添加到包含the的每一行后
[root@centos ~]# sed '3ahahaha' aaa //在第3行后插入一个新行,内容为hahaha
[root@centos ~]# sed '/PI/ahahaha' aaa //在包含PI的每一行后插入hahaha
[root@centos ~]# sed '3ahaha\nhaha2' aaa //在第三行后插入多行内容,\n表示换行