1. 程式人生 > >sed 命令使用(1)

sed 命令使用(1)

sed 簡單說明:SED是流編輯器。流編輯器用於執行基本文字對輸入流(檔案或管道的輸入)的轉換。雖然在某些方面類似於允許指令碼編輯的編輯器。
例項
1:用sed取出指定行
[[email protected] scripts]# cat color.sh #原始檔
#!/bin/sh
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
RES='\E[0m'
echo -e "$RED_COLOR ==WER== $RES"
[[email protected]

scripts]# sed  -n '2,3p' color.sh
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
[[email protected] scripts]#
[[email protected] scripts]#
[email protected] scripts]# sed -n '/RES/p' color.sh 
RES='\E[0m'
echo -e "$RED_COLOR ==WER== $RES"
[[email protected] scripts]#
說明:-n :取消預設輸出;輸出指定的;'2,3p'輸出2到3行p是列印;指定內容輸出它所在行
如不加 -n 輸出結果是:
[
[email protected]
scripts]# sed   '2,3p' color.sh
#!/bin/sh
RED_COLOR='\E[1;31m'
**RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'**
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
RES='\E[0m'
echo -e "$RED_COLOR ==WER== $RES"
2:刪除指定內容
[[email protected] scripts]# sed  '2,3d' color.sh #刪除2-3的內容;
#!/bin/sh
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
RES='\E[0m'
echo -e "$RED_COLOR ==WER== $RES"
[
[email protected]
scripts]# sed  '/YELLOW_COLOR/d' color.sh #刪除指定內容行
#!/bin/sh
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
RES='\E[0m'
echo -e "$RED_COLOR ==WER== $RES"
[[email protected] scripts]#
說明:d:是刪除;但不是真正的刪除了檔案裡的內容;只是在終端不打印出來;加上 -i 才能修改檔案的內容如:sed -i '/YELLOW_COLOR/d' color.sh;真正要修改檔案時才用
3:替換指定內容
替換格式 sed 's#源資料#替換資料#g' 檔名 或 sed 's/源資料/替換資料/g' 檔名;s:是取代;g:是全域性替換
[[email protected] scripts]# sed  's#RES#123#g' color.sh 
#!/bin/sh
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
123='\E[0m'
echo -e "$RED_COLOR ==WER== $123"
[[email protected] scripts]#
4:用sed 替換得到IP
”.“ 點代表且只能代表任意一個字元(不匹配空行)
”*“ 星代表重複之前的字元或文字0個或多個,之前的文字或字元連續0次或多
”.*“ 點星代表任意多個字元
sed 's#.*inet ##g' 把包含ine前的內容全部替換空;
sed 's# netmask.*##g' 把包含netmask以後的內容全部替換空
[[email protected] scripts]# ifconfig enp0s3|grep 'inet '|sed 's#.*inet ##g'|sed 's# netmask.*##g'
192.168.0.3
[[email protected] scripts]#