linux運維開發(五)----------三劍客之sed

sed的特點:

sed同awk一樣都是行處理器,不過不同的是awk針對記錄進行分割顯示,而sed則主要用於對記錄進行修改

sed使用場景

替換關鍵字,例如在redis部署中,如果需要部署多個redis實例,則需要根據端口創建不同的配置文件,我們則可以這樣做:

sed ‘s#6379#6380#g’ 6379.conf > 6380.conf

通過以下shell命令可以實現一次生成多個配置文件:

for port in $(seq 6380 6385); do sed ‘s#6379#${port}#g’ 6379.conf > ${port}.conf; done;

sed命令詳解:

命令參數:

  • 取消默認輸出參數:-n
  • 連續編輯參數:-e
  • 將修改作用到文件參數:-i

命令選項:

打印信息選項:p

打印包含root到包含mysql範圍的所有行:

sed -n ‘/root/,/mysql/p’ test.txt

打印行號:=

打印包含root到包含mysql範圍的所有行的行號:

sed ‘/root/,/mysql/=’ test.txt

行追加選項:a

在第一行行追加hello wold字符串

sed ‘1a hello world’ test.txt

在第一行到第三行每行後面追加hello world字符串

sed ‘1,3a hello world’ test.txt

在第三行到最後一行每行後面追加hello world字符串

sed ‘3,$a hello world’ test.txt

行插入選項:i

在包含mysql的行到最後一行的每行前插入hello world字符串

sed ‘/mysql/,$i hello world’ test.txt

在第三行到包含mysql的行的每行前插入hello world字符串

sed ‘3,/mysql/i hello world’ test.txt

在包含root到包含mysql範圍的每行前插入hello world字符串

sed ‘/root/,/mysql/i hello world’ test.txt

行替換選項:c

除第3行到第5行的其他替換爲hello world字符串

sed ‘3,5!c hello world’ test.txt

將包含bash的行替換爲hello world字符串

sed ‘/bash/c hello world’ test.txt

行刪除選項:d

刪除包含nologin的行:

sed ‘/nologin/d’ test.txt

刪除空行:

sed ‘/^$/d’ test.txt

刪除以數字開頭的行:

sed ‘/^[0-9][0-9]*/d’ test.txt

刪除以字母結尾的行:

sed ‘/^[A-Z a-z][A-Z a-z]*/d’ test.txt

全局選項:g
替換字符串選項:s

替換mysql爲oracle:

sed ‘s/mysql/oracle/g’ test.txt

替換多個空格爲一個空格:

sed ‘s/[ ][ ]*/ /g’ netstat.txt

如果空格與TAB共存時用下面的命令進行替換:

sed ‘s/[[:space:]][[:space:]]*/ /g’ netstat.txt

sed中( )和\1的功能:

  • 打印ifconfig中的IP地址

ifconfig | sed -n ‘s#^.*inet (.*) netmask.*$#\1#gp’

或者

ifconfig | sed -n ‘s#^.*inet[ ]*(.*)[ ]*netmask.*$#\1#gp’

或者(該命令不顯示本地的127.0.0.1地址)
不顯示本地的127.0.0.1地址

上述選項中匹配行的方式可以相互使用

更多問題可以加公衆號:代碼小棧,期待爲您解決更多問題
代碼小棧

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章