[sh]sed 4个功能

[root@lanny test]# cat test.txt 
test
liyao
lanny

 


经典博文:

http://oldboy.blog.51cto.com/2561410/949365

http://blog.csdn.net/hello_hwc/article/details/39528879 

http://blog.csdn.net/hello_hwc/article/details/39528879


 SSH优化:在某一行后追加内容

sed -ir '13 iPort 52113\nPermitRootLogin no\nPermitEmptyPasswords no\nUseDNS no\nGSSAPIAuthentication no' sshd_config


在13行后追加这些内容

 


 

############################################

-n, --quiet, --silent  ----suppress automatic printing of pattern space

-i   [SUFFIX], --in-place[=SUFFIX]

-r 正则

p Print the current pattern space.

注:

pattern有鞋样子的意思.  正则表达式就是个鞋样子.

in place of 代替

in place 在对的位置; 适当的;

############################################

1,取行

[root@lanny test]# sed -n '3p' test.txt 
jeffery
[root@lanny test]# sed -n '2,3p' test.txt 
liyao
jeffery

2,过滤

[root@lanny test]# sed -n '/liyao/p' test.txt 
liyao
删除第三行:
sed -n '/3/d' test.txt

 

3,拼凑

知识点:sed后向引用:(全屏蔽取出思想)

[root@lanny ~]# echo "oldboy oldgirl"|sed -r 's#(.*) (.*)#\1 \2#g'
oldboy oldgirl

注解:

()的作用: 's#(.*) (.*) 正则的书写,显然我们后面的()都不希望被转义
--r的作用:sed -r ,加入后面要匹配的空格符号不希望被转义,那么就加-r选项了.
1 sed -r 's#(.*)#chkconfig \1 off#g'
2 -r 不转义 后面的括号等为原来意义
3 (.*) 过滤出输出的内容 括起来 后面可以通过 \1取出来

[root@lanny test]# sed -r 's#(.*)#chkconfig \1 off#g' test.txt
chkconfig test off
chkconfig liyao off
chkconfig jeffery off

 

拼凑特例:=========================可能不好理解 grep ^ file.txt 发现什么也没匹配,

思想:什么都没屏蔽

但是这样报错呀:

[root@lanny l]# sed -r 's##a b #g' name.txt
sed: -e expression #1, char 0: no previous regular expression

======================================必须得加个东西了,那就加^吧.哈哈,也算是理解了.

[root@lanny l]# sed -r 's#^##g' name.txt
liyao
oldboy
test
[root@lanny l]# sed -r 's#^#a b #g' name.txt
a b liyao
a b oldboy
a b test

sed什么参数都不加,凭凑在最后了

思想:匹配到,替换掉.

情况一:用^匹配:
[root@lanny data]# sed 's#^#chkconfig on #g' name.txt 
chkconfig on oldlanny
chkconfig on jack
chkconfig on jeffery
chkconfig on liming

情况二:用$匹配:chkconfig没加上,只匹配到最后一部分.

[root@lanny ~]# sed -r 's#$#chkconfig on #g' aa
maxiaolangchkconfig on
lannychkconfig on
lannyma.blog.51cto.comchkconfig on

 awk也可以拼凑:

awk '{print $1}'

进阶:
awk '{print "chkconfig " $1 " on"}'

 

sed结合正则表达式过滤ip地址:

[root@lanny ~]# ifconfig eth0|sed -n '2p'
          inet addr:192.168.14.134  Bcast:192.168.14.255  Mask:255.255.255.0
[root@lanny ~]# 
[root@lanny ~]# ifconfig eth0|sed -n '2p'|sed -r 's#^.*addr:##g'
192.168.14.134  Bcast:192.168.14.255  Mask:255.255.255.0
[root@lanny ~]# 
[root@lanny ~]# ifconfig eth0|sed -n '2p'|sed -r 's#^.*addr:##g'|sed -r 's# B.*$##g'
192.168.14.134

前2个##匹配到的过滤掉(删掉)输出.

sed -r 's#^.*addr:##g'

4,替换

 

[root@lanny test]# sed -i 's#lanny#jeffery#g' test.txt 
[root@lanny test]# cat test.txt 
test
liyao
jeffery
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值