sed 命令使用(1)

sed 简单说明:SED是流编辑器。流编辑器用于执行基本文本对输入流(文件或管道的输入)的转换。虽然在某些方面类似于允许脚本编辑的编辑器。
实例
1:用sed取出指定行
[root@localhost scripts]# cat color.sh #源文件
#!/bin/sh
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
RES='\E[0m'
echo -e "$RED_COLOR ==WER== $RES"
[root@localhost scripts]# sed  -n '2,3p' color.sh
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
[root@localhost scripts]#
[root@localhost scripts]#
root@localhost scripts]# sed -n '/RES/p' color.sh 
RES='\E[0m'
echo -e "$RED_COLOR ==WER== $RES"
[root@localhost scripts]#
说明:-n :取消默认输出;输出指定的;'2,3p'输出2到3行p是打印;指定内容输出它所在行
如不加 -n 输出结果是:
[root@localhost scripts]# sed   '2,3p' color.sh
#!/bin/sh
RED_COLOR='\E[1;31m'
**RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'**
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
RES='\E[0m'
echo -e "$RED_COLOR ==WER== $RES"
2:删除指定内容
[root@localhost scripts]# sed  '2,3d' color.sh #删除2-3的内容;
#!/bin/sh
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
RES='\E[0m'
echo -e "$RED_COLOR ==WER== $RES"
[root@localhost scripts]# sed  '/YELLOW_COLOR/d' color.sh #删除指定内容行
#!/bin/sh
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
RES='\E[0m'
echo -e "$RED_COLOR ==WER== $RES"
[root@localhost scripts]#
说明:d:是删除;但不是真正的删除了文件里的内容;只是在终端不打印出来;加上 -i 才能修改文件的内容如:sed -i '/YELLOW_COLOR/d' color.sh;真正要修改文件时才用
3:替换指定内容
替换格式 sed 's#源数据#替换数据#g' 文件名 或 sed 's/源数据/替换数据/g' 文件名;s:是取代;g:是全局替换
[root@localhost scripts]# sed  's#RES#123#g' color.sh 
#!/bin/sh
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
123='\E[0m'
echo -e "$RED_COLOR ==WER== $123"
[root@localhost scripts]#
4:用sed 替换得到IP
”.“ 点代表且只能代表任意一个字符(不匹配空行)
”*“ 星代表重复之前的字符或文本0个或多个,之前的文本或字符连续0次或多
”.*“ 点星代表任意多个字符
sed 's#.*inet ##g' 把包含ine前的内容全部替换空;
sed 's# netmask.*##g' 把包含netmask以后的内容全部替换空
[root@localhost scripts]# ifconfig enp0s3|grep 'inet '|sed 's#.*inet ##g'|sed 's# netmask.*##g'
192.168.0.3
[root@localhost scripts]#

猜你喜欢

转载自blog.csdn.net/LINU_BW/article/details/84843587