sed 本身是一個管道命令,可以分析標準輸入。而且sed 還可以將數據進行替換,刪除,新增,選取特定行等功能。
sed :
參數:
-n 使用安靜模式。一般所有來自STDIN的數據一般都會列出到屏幕上,但是加上 -n 以後,則只顯示經過sed 處理的數據纔會被列出來。、
-f 直接講sed 的動作寫在一個文件內,-f filename 則你可以執行 filename 內的sed 動作
-r sed的動作支持擴展正則表達式語法
-e 直接在命令行進行sed的動作編輯
-i 直接修改讀取文件內容,不是由屏幕輸出
動作說明: [n1 [,n2]] function
n1, n2 一般是選擇命令執行的行數 。 例如 10,20 [function]
function 有以下參數
a :新增,a的後面可以接字符串,這些字符串會在目標行下一行顯示。
c :替換,c的後面可以接字符串,這些字符串會替代n1,n2行之間的內容。
d :刪除,因爲是刪除,所以d後面通常不接任何參數
i :插入,i 的後面可以接字符串,這些字符串會在新的一行出現(目標行的上一行)。
p : 打印, 也就是將所選的行數打印出來,通常與sed -n 同時使用。
s : 替換,通常搭配正則表達式一起使用,----------------sed 's/被替換字符串/替換字符串/g'
root@pwx-pc:/tmp/pwxTest# nl vimrcNew | grep 'the' | sed '2a Hallo' //第二行的下面
1 " the call to :runtime you can find below. If you wish to change any of those
2 " will be overwritten everytime an upgrade of the vim packages is performed.
Hallo
3 " the value of the 'compatible' option.
4 " properly set to work with the Vim-related packages available in Debian.
5 " Uncomment the next line to make Vim more Vi-compatible
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
root@pwx-pc:/tmp/pwxTest# nl vimrcNew | grep 'the' | sed '2i Hallo' //第二行的上面
1 " the call to :runtime you can find below. If you wish to change any of those
Hallo
2 " will be overwritten everytime an upgrade of the vim packages is performed.
3 " the value of the 'compatible' option.
-------------------------------------------------------------------------------------------------------------------
root@pwx-pc:/tmp/pwxTest# nl vimrcNew |
sed -n '1,3p' //選擇1-3 行進行輸出
1 " All system-wide defaults are set in $VIMRUNTIME/debian.vim and sourced by
2 " the call to :runtime you can find below. If you wish to change any of those
3 " settings, you should do it in this file (/etc/vim/vimrc), since debian.vim
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
root@pwx-pc:/tmp/pwxTest# nl vimrcNew | sed -n '1,3p' | sed 's/^.*"//g'
//從開通一直到雙引號("),用空白進行替換
All system-wide defaults are set in $VIMRUNTIME/debian.vim and sourced by
the call to :runtime you can find below. If you wish to change any of those
settings, you should do it in this file (/etc/vim/vimrc), since debian.vim
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
root@pwx-pc:/tmp/pwxTest# nl vimrcNew | sed -n '1p' | sed 's/^.*"//g'
All system-wide defaults are set in $VIMRUNTIME/debian.vim and sourced by
root@pwx-pc:/tmp/pwxTest# nl vimrcNew | sed -n '1p' | sed 's/^.*"//g'|sed 's/\/.*$//g'
All system-wide defaults are set in $VIMRUNTIME
由上面的指令到下面的指令,可見輸的結果有不一樣的
總結:
從開頭到一個字符串 進行替換,表達式寫法:sed n1,n2's/^.*被替換字符串/替換字符串/g'
從被替換字符串到結尾,表達式寫法:
sed n1,n2's/被替換字符串.*$/替換字符串/g'