標籤:sed用法
前言:記錄基本的sed用法。
內容:
基本的工具grep ,sed(流編輯器),awk。650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/4B/AD/wKioL1QvsQDCtBcUAAC6gGdgQY0613.jpg" title="捕獲2.PNG" alt="wKioL1QvsQDCtBcUAAC6gGdgQY0613.jpg" />
注意事項:sed預設是不對源檔案進行修改(-i選項能夠修改源檔案)
sed的基本用法:
sed: Stream EDitor
行編輯器 (全屏編輯器: vi)
sed: 模式空間
預設不編輯原檔案,僅對模式空間中的資料做處理;而後,處理結束後,將模式空間列印至螢幕;
sed [options] ‘AddressCommand‘ file ...
option:-n: 靜默模式,不再預設顯示模式空間中的內容
-i: 直接修改原檔案
-e SCRIPT -e SCRIPT:可以同時執行多個指令碼
-f /PATH/TO/SED_SCRIPT
sed -f /path/to/scripts file
-r: 表示使用擴充Regex
Address:
1、StartLine,EndLine
比如1,100
$:最後一行
2、/RegExp/(Regex)
/^root/
3、/pattern1/,/pattern2/
第一次被pattern1匹配到的行開始,至第一次被pattern2匹配到的行結束,這中間的所有行
4、LineNumber
指定的行
5、StartLine, +N
從startLine開始,向後的N行。
Command:
d: 刪除合格行;
p: 顯示合格行;
a \string: 在指定的行後面追加新行,內容為string
\n:可以用於換行
i \string: 在指定的行前面添加新行,內容為string
r FILE: 將指定的檔案的內容添加至合格行處
w FILE: 將地址指定的範圍內的行另存至指定的檔案中;
s/pattern/string/修飾符: 尋找並替換,預設只替換每行中第一次被模式比對到的字串
加修飾符
g: 全域替換
i: 忽略字元大小寫
s///: s###, [email protected]@@
\(\), \1, \2
l..e: like-->liker
love-->lover
like-->Like
&: 參考模式匹配整個串
3.練習:
sed ‘1,3d‘ /etc/fstab
sed -n ‘1,6p‘ /etc/fstab
sed -n ‘/^#/p‘ /etc/fstab
sed -n ‘/oot/p‘ /etc/fstab
sed -n ‘6,$p‘ /etc/fstab
sed -n ‘10,+5p‘ /etc/fstab
sed ‘/^[[:space:]]*/d‘ /etc/fstab
sed ‘/^[[:space:]]*/‘ /etc/fstab
sed ‘/^\//d‘ /etc/fstab
sed -n ‘/^L/a \#hello world‘ /etc/fstab
sed ‘/^L/i \#hello world \n #hello linux‘ /etc/fstab
sed ‘1,2r /etc/issue‘ /etc/fstab
sed ‘1,2w /var/w.txt‘ /etc/fstab
sed ‘s/oot/OOT/‘ /etc/fstab
sed ‘s/^#/\//g‘ /etc/fstab
sed ‘s#l..e#&r#‘ 001
sed ‘s#\(l..e\)#\1r#‘ /etc/fstab
sed ‘s#l\(..e\)#L\1#‘ 001
sed練習:
1、刪除/etc/grub.conf檔案中行首的空白符;
sed -r ‘[email protected]^[[:spapce:]][email protected]@g‘ /etc/grub.conf
2、替換/etc/inittab檔案中"id:3:initdefault:"一行中的數字為5;
sed ‘[email protected]\(id:\)[0-9]\(:initdefault:\)@\15\[email protected]‘ /etc/inittab
3、刪除/etc/inittab檔案中的空白行;
sed ‘/^$/d‘ /etc/inittab
4、刪除/etc/inittab檔案中開頭的#號;
sed ‘[email protected]^#@@g‘ /etc/inittab
5、刪除某檔案中開頭的#號及後面的空白字元,但要求#號後面必須有空白字元;
sed -r ‘[email protected]^#[[:space:]][email protected]@g‘ /etc/inittab
6、刪除某檔案中以空白字元後面跟#類的行中的開頭的空白字元及#
sed -r ‘[email protected]^[[:space:]]+#@@g‘ /etc/inittab
7、取出一個檔案路徑的目錄名稱;
echo "/etc/rc.d/" | sed -r ‘[email protected]^(/.*/)[^/]+/[email protected]\[email protected]‘
基名:
echo "/etc/rc.d/" | sed -r ‘[email protected]^/.*/([^/]+)/[email protected]\[email protected]‘
總結:總結還不太完整,後續添加。
本文出自 “天道酬勤” 部落格,謝絕轉載!
linux學習筆記六(sed基本用法)