您的位置:首页 > 运维架构 > Shell

Shell之Sed命令-yellowcong

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

替换命令

全面替换标记g

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

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

#替换所有的name
echo 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 tick
tickTime=2000
# The number of ticks that the initial
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between
# sending a request and getting an acknowledgement
syncLimit=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 connect
clientPort=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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: