sed是一個非交互性的流編輯器,是stream editor的縮寫。sed每次只處理一行內容,可以對文本或標准輸入流進行處理。需要注意的是,sed並不直接操作初始數據,它操作的是一份原始數據的拷貝。sed處理時,把當前處理的行存儲在臨時緩沖區中,然後處理緩沖區中的內容,處理完成後,如果沒有重定向到文件, 將把緩沖區中的內容送往屏幕,接著處理下一行直到處理完畢。
理論的東東,這裡不談了,下面談些常規應用吧。
在演示之前,我們先構築個初始文件orig.txt 和append.txt
- [root@localhost .shell]# cat orig.txt
- id name price address
- --------------------------------
- 1 apple $50 USA
- 2 pear $60 Canda
- 3 pen $1 China
- --------------------------------
- total $111
- [root@localhost .shell]# cat append.txt
- 4 apple $50 USA
- 5 $60 Canda
- 6 pen $1 China
1、打印指定行
a)打印第一行
- [root@localhost .shell]# sed -n '1p' orig.txt
- id name price address
b)打印3-5行
- [root@localhost .shell]# sed -n '3,5p' orig.txt
- 1 apple $50 USA
- 2 pear $60 Canda
- 3 pen $1 China
c)打印最後一行
- [root@localhost .shell]# sed -n '$p' orig.txt
- total $111
d)打印所有行
- [root@localhost .shell]# sed -n '1,$p' orig.txt
- id name price address
- -------------------------------
- 1 apple $50 USA
- 2 pear $60 Canda
- 3 pen $1 China
- --------------------------------
- total $111
e)打印含有pen的行
- [root@localhost .shell]# sed -n '/pen/p' orig.txt
- 3 pen $1 China
f)從第一行開始打印,打印到第一個含有$行
- [root@localhost .shell]# sed -n '1,/\$/'p orig.txt
- id name price address
- -------------------------------
- 1 apple $50 USA