一、sed简介
sed 是 stream editor 的缩写,流编辑器,主要用于对标准输出或文件进行逐行处理。
二、语法
语法格式
- stdout | sed [option] "pattern command" #对 | 前面输出的内容进行sed处理
- sed [option] "pattern command" file
option选项
- -n 只打印模式匹配行
- -f 编辑动作保存在文件中,-f 指定要执行的文件
- -e 直接在命令行进行sed编辑,默认选项
- -r 支持扩展正则表达式
- -i 直接修改文件内容
动作说明:
- a :新增, a 的后面可以接字串,而这些字串会在新的一行出现(目前的下一行)~
- c :取代, c 的后面可以接字串,这些字串可以取代 n1,n2 之间的行!
- d :删除,因为是删除,所以 d 后面通常不接任何东西;
- i :插入, i 的后面可以接字串,而这些字串会在新的一行出现(目前的上一行);
- p :打印,亦即将某个选择的数据印出。通常 p 会与参数 sed -n 一起运行~
- s :取代,可以直接进行取代,通常这个 s 的动作可以搭配正则表示法
- s/old/new 替换行内第一个 old 为 new
- s/old/new/g 行内所有 old 替换为 new
- s/old/new/2g 从第 2 行开始到文件末尾的所有 old 替换为 new
- s/old/new/ig 行内所有 old 替换为 new,忽略大小写
匹配模式(pattern)

三、实例
1、指定行前后追加内容
原文件test_sed.sh内容:
HELLO LINUX!
Linux is a free unix-type opterating system.
This is a linux testfile!
Linux test
在testfile文件的第四行后添加一行,并将结果输出到标准输出,在命令行提示符下输入如下命令:
[root@liang shell]# sed -e '4 a newLine' test_sed.sh
HELLO LINUX!
Linux is a free unix-type opterating system.
This is a linux testfile!
Linux test
newLine
a 动作是在匹配的行之后追加字符串,追加的字符串中可以包含换行符(实现追加多行的情况)
追加一行的话前后都不需要添加换行符 \n
追加多行
sed -e '4 a newline\nnewline2' test_sed.sh
同理,指定行前插入内容
sed -e '4 i newline\nnewline2' test_sed.sh
2、打印指定行
打印第3-4行
Linux test [root@liang shell]# sed -n '3,4p' test_sed.sh
3、修改指定行为新的文本
将第二行内容修改为111
sed '2c 111' test_sed.sh
4、删除选中的行
sed '2,5d' test_sed.sh 删除2~5行
sed '/^#/d' test_sed.sh 删除以#开头的行
sed '/^#/,/8$/d' test_sed.sh 删除以#开头以8结尾的行,如果找不到8结尾的,会删除#开头的之后的所有行
sed '/^$/d' test_sed.sh 删除空行
5、替换指定字符串
sed 's/#Port 22/Port 2200/g' test_sed.sh #将‘#Port 22’替换为‘Port 2200’
6、数据的搜寻并显示
搜索有root关键字的行
sed -n '/root/p' test_sed.sh
7、使用拓展正则 -r
匹配有连续5位数字的行
sed -nr '/[0-9]{5}/ p' test_sed.sh
8、多个命令之间以分号隔开
sed -i '/root/ {p;s/#Port 22/Port 2200/g;/^#/d;/^$/d}' test_sed.sh
或者
sed -n '/root\|daemon/p' test_sed.sh
sed -n '/root/{/daemon/p}' test_sed.sh
网友评论