歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux sed常規用法小結

Linux sed常規用法小結

日期:2017/2/28 15:56:14   编辑:Linux教程

sed是一個非交互性的流編輯器,是stream editor的縮寫。sed每次只處理一行內容,可以對文本或標准輸入流進行處理。需要注意的是,sed並不直接操作初始數據,它操作的是一份原始數據的拷貝。sed處理時,把當前處理的行存儲在臨時緩沖區中,然後處理緩沖區中的內容,處理完成後,如果沒有重定向到文件, 將把緩沖區中的內容送往屏幕,接著處理下一行直到處理完畢。

理論的東東,這裡不談了,下面談些常規應用吧。

在演示之前,我們先構築個初始文件orig.txt 和append.txt

  1. [root@localhost .shell]# cat orig.txt
  2. id name price address
  3. --------------------------------
  4. 1 apple $50 USA
  5. 2 pear $60 Canda
  6. 3 pen $1 China
  7. --------------------------------
  8. total $111
  9. [root@localhost .shell]# cat append.txt
  10. 4 apple $50 USA
  11. 5 $60 Canda
  12. 6 pen $1 China

1、打印指定行

a)打印第一行

  1. [root@localhost .shell]# sed -n '1p' orig.txt
  2. id name price address

b)打印3-5行

  1. [root@localhost .shell]# sed -n '3,5p' orig.txt
  2. 1 apple $50 USA
  3. 2 pear $60 Canda
  4. 3 pen $1 China

c)打印最後一行

  1. [root@localhost .shell]# sed -n '$p' orig.txt
  2. total $111

d)打印所有行

  1. [root@localhost .shell]# sed -n '1,$p' orig.txt
  2. id name price address
  3. -------------------------------
  4. 1 apple $50 USA
  5. 2 pear $60 Canda
  6. 3 pen $1 China
  7. --------------------------------
  8. total $111

e)打印含有pen的行

  1. [root@localhost .shell]# sed -n '/pen/p' orig.txt
  2. 3 pen $1 China

f)從第一行開始打印,打印到第一個含有$行

  1. [root@localhost .shell]# sed -n '1,/\$/'p orig.txt
  2. id name price address
  3. -------------------------------
  4. 1 apple $50 USA
Copyright © Linux教程網 All Rights Reserved