Shell之Sed命令-yellowcong

来源:互联网 发布:东莞天行健网络怎么样 编辑:程序博客网 时间:2024/06/05 07:19

Sed可以用来替换文本,sed -i '/xx/xxx/p' file来替换文件类容,-i表示更改文件,如果不加上参数-i,只是替换了,但是没有写入到文件里面。还有,路径的替换是比较特殊的,需要特别的注意

替换命令

全面替换标记g

使用后缀 /g 标记会替换每一行中的所有匹配:

当需要从第N处匹配开始替换时,可以使用 /Ng:

#替换所有的nameecho name_xx_name_xx2 | sed 's/name/NAME/g'#替换第二次的name为大写echo name_xx_name_xx2 | sed 's/name/NAME/2g'

查看结果,可以看到,这个 g可以替换当前行的第几个

这里写图片描述

路径替换

zoo_sample.cfg配置文件,实验替换文件

# The number of milliseconds of each ticktickTime=2000# The number of ticks that the initial# synchronization phase can takeinitLimit=10# The number of ticks that can pass between# sending a request and getting an acknowledgementsyncLimit=5# the directory where the snapshot is stored.# do not use /tmp for storage, /tmp here is just# example sakes.dataDir=/tmp/zookeeper# the port at which the clients will connectclientPort=2181# the maximum number of client connections.# increase this if you need to handle more clients#maxClientCnxns=60## Be sure to read the maintenance section of the# administrator guide before turning on autopurge.## http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance## The number of snapshots to retain in dataDir#autopurge.snapRetainCount=3# Purge task interval in hours# Set to "0" to disable auto purge feature#autopurge.purgeInterval=1

路径的替换,需要结合#好表示替换的类容,而不是分号来替换

#查找/tmp/zookeeper 的文件sed -n '/\/tmp\/zookeeper/p' test.cfg#替换路径的操作sed -i 's#/tmp/zookeeper#/tmp/zookeeper1/data#' test.cfg

这里写图片描述

追加行

#在/dataDir/ 后面添加一行sed -i '/^dataDir/a\dataLogDir=\/tmp\/zookeeper1\/logs' test.cfg#在dataDir 前面添加一样sed -i '/^dataDir/i\dataLogDir=\/tmp\/zookeeper1\/logs' test.cfg

在后面添加数据,参数是 a(after),
这里写图片描述

在前面添加数据,参数是i(insert)
这里写图片描述

文件头/尾追加

#追加的数据太长了,所以使用了 \ 进行了换行的操作sed -i '$a \server.1=127.0.0.1:2222:2225 \    server.2=127.0.0.1:3333:3335 \    server.3=127.0.0.1:4444:4445 \    ' test.cfg#在文件的第一行添加文件sed -i '1 i\fisrt file' test.cfg

添加成功
这里写图片描述

最后一行添加

删除命令

删除的操作,可以删除哪一行,也可以设定匹配删除哪一行的数据

行删除

#删除第一行sed -i '1d' test.cfg#删除第二行,第三行,第四行有此类推sed -i '2d' test.cfg#删除最后一行sed -i '$d' test.cfg

这里写图片描述

匹配删除

sed -i '//d' test.cfg

这里写图片描述

查找命令

查找文件行数据

#查找文件的第二行sed -n  '2p' zoo.cfg#打印文件的1-6 行的数据sed -n '1,6p' zoo.cfg#打印以data开头的行sed -n '/^data/p' zoo.cfg

这里写图片描述

参考文章

http://www.cnblogs.com/ctaixw/p/5860221.html
http://man.linuxde.net/sed#sed%E6%9B%BF%E6%8D%A2%E6%A0%87%E8%AE%B0
http://blog.csdn.net/loveaborn/article/details/17269645

原创粉丝点击