Sed可以用來替換文本,
sed -i '/xx/xxx/p' file
來替換文件類容,-i表示更改文件,如果不加上參數-i,只是替換了,但是沒有寫入到文件裏面。還有,路徑的替換是比較特殊的,需要特別的注意
替換命令
替換路徑
Mac上使用sed命令時,報出sed: 1: “1.txt”: invalid command code .錯誤。是由於Mac上sed命令與linux下稍有不同。Mac上默認提供修改時的備份機制。
sed -i "" "s#E:\\\\開發\\\\yellow\\\\images\\\\#../images/#g" ./README.md
#需要備份的情況
sed -i ".bak" 's/string_old/string_new/g' grep -rl 'string_old' ./
全面替換標記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替換標記
http://blog.csdn.net/loveaborn/article/details/17269645