天天看點

9.4 sed(上);9.5 sed(下)

9.4 sed(上)

1. 建立目錄 :              

[root@hao-01 ~]# mkdir sed

2. 進入目錄 :                  

[root@hao-01 ~]# cd sed

3. 拷貝/etc/passwd到目前目錄,并重命名 :

[root@hao-01 sed]# cp /etc/passwd   test.txt

比對指定行:

1. 比對 含有關鍵詞(root)行:

sed -n '/關鍵詞/'p 檔案名

[root@hao-01 sed]# sed -n '/root/'p test.txt

2. 比對 關鍵詞.關鍵詞(點,一個任意字元)的行 :

sed -n '/關鍵詞.關鍵詞/'p 檔案名

[root@hao-01 sed]# sed -n '/r.t/'p test.txt

3. 比對 *星号右邊關鍵詞的行,全部列印出來:

sed -n '/任意關鍵詞*關鍵詞/'p 檔案名

[root@hao-01 sed]# sed -n '/r*t/'p test.txt

4. 比對 關鍵詞+關鍵詞(ot組合);sed -nr 作用于 +加号 :

sed -nr '/關鍵詞+關鍵詞/'p 檔案名

[root@hao-01 sed]# sed -nr '/o+t/'p test.txt

5. 比對 關鍵詞任意次(n次) :

sed -nr '/關鍵詞{比對次數}/'p 檔案名

[root@hao-01 sed]# sed -nr '/o{2}/'p test.txt

6. 比對 關鍵詞1或者比對關鍵詞2或者比對關鍵詞3 :

sed -nr '/關鍵詞1|關鍵詞2|關鍵詞3/'p 檔案名

[root@hao-01 sed]# sed -nr '/root|hao|sbin/'p test.txt

列印指定行:

7. 列印 指定行:

sed -nr '指定行'p 檔案名

[root@hao-01 sed]# sed -nr '2'p test.txt

8. 列印 指定範圍行:

sed -nr '指定範圍行'p 檔案名

[root@hao-01 sed]# sed -nr '2,5'p test.txt

9. 列印指定行到末行($):

sed -nr '指定行,$'p 檔案名

[root@hao-01 sed]# sed -nr '2,$'p test.txt

10. 列印全部行(第一行到末行):

sed -nr '1,$'p 檔案名

[root@hao-01 sed]# sed -nr '1,$'p test.txt

11. 列印指定行,還可以比對包含關鍵詞1的行和比對包含關鍵詞2的行 :

sed -e '指定行'p -e '/比對關鍵詞1/'p -e '/比對關鍵詞2/'p -n 檔案名

[root@hao-01 sed]# sed -e '1'p -e '/111/'p -e '/hao/'p -n test.txt

9.5 sed(下)

1. 比對 含有關鍵詞(root)行,但不區分大小寫:

sed -n '/關鍵詞/'Ip 檔案名

[root@hao-01 sed]# sed -n '/root/'Ip test.txt

2. 不比對 指定的範圍行,其餘行列印到螢幕(隻限于生效在螢幕) :

sed '範圍行'd test.txt

[root@hao-01 sed]#sed '1,10'd test.txt

3. 删除 檔案中指定的範圍行(生效在檔案):

sed -i '範圍行'd test.txt

[root@hao-01 sed]# sed -i '1,10'd test.txt

檢視檔案行數:wc -l 檔案名

[root@hao-01 sed]# wc -l test.txt

4. 删除 檔案中含有關鍵詞的行(生效在檔案):

sed -i '/關鍵詞/'d 檔案名

[root@hao-01 sed]# sed -i '/hao/'d test.txt

5. 查找指定行,并全局替換 列印到螢幕:

sed '指定範圍行s/關鍵詞/替換關鍵詞/g' test.txt

[root@hao-01 sed]# sed '1,10s/hao/root/g' test.txt

head 預設是輸出檔案内容的前十行!!!

6. 查找指定範圍行,并用正規表達式+号進行了全局替換  後面可以用管道符 :

[root@hao-01 sed]# sed -r '1,10s/ro+/r/g' test.txt |head

7. 把前面指令的輸出結果, 管道符丢給sed指令,以冒号分隔為一段,每行的第一段和最後一段互相替換:

[root@hao-01 sed]# head test.txt |sed -r 's/([^:]+):(.*):([^:]+)/\3:\2:1/'

8. head 輸出檔案前十行,sed 查找關鍵詞1 替換 關鍵詞2 :

(預設指令用法中分隔符/,可以用@或#代替都OK啦)

把關鍵詞:/sbin/nologin  替換成 123 ,因為被替換關鍵詞有/斜杠,就用@為指令分隔符了

[root@hao-01 sed]# head test.txt |sed 's@/sbin/nologin@123@g'

9. 前十行替換, 字母範圍為空 :

head 檔案名 |sed 's/[小寫大寫字母範圍]//g'

[root@hao-01 sed]# head test.txt |sed 's/[a-zA-Z]//g'

9.4 sed(上);9.5 sed(下)

10. 所有行行首,添加強定的字元串:

head 檔案名 |sed -r 's/(.*)/添加的字元串:&/'

[root@hao-01 sed]# head test.txt |sed -r 's/(.*)/hhh:&/'

9.4 sed(上);9.5 sed(下)

本文轉自 主内安詳 51CTO部落格,原文連結:http://blog.51cto.com/zhuneianxiang/2061641,如需轉載請自行聯系原作者