天天看點

sed 擴充

練習題:(第一次做題10-13都不會做)

1、把/etc/passwd 複制到/root/test.txt,用sed列印所有行

[root@centos7-2 tmp]# cat /etc/passwd > /root/test.txt && sed -n '1,$'p /root/test.txt

2、列印test.txt的3到10行

sed -n '3,10p' test.txt

3、列印test.txt 中包含 ‘root’ 的行

sed -n '/root/p' test.txt

4、删除test.txt 的15行以及以後所有行

sed '15,$'d test.txt

5、删除test.txt中包含 ‘bash’ 的行

sed '/bash/'d test.txt

6、替換test.txt 中 ‘root’ 為 ‘toor’

sed 's#root#toor#g' test.txt

7、替換test.txt中 ‘/sbin/nologin’ 為 ‘/bin/login’

sed 's#\/sbin\/nologin#\/bin\/login#g' test.txt

8、删除test.txt中5到10行中所有的數字

sed -n '5,10p' test.txt |sed 's#[0-9]##g'

9、删除test.txt 中所有特殊字元(除了數字以及大小寫字母)

sed 's#[^A-Za-z0-9]##g' test.txt

10、把test.txt中第一個單詞和最後一個單詞調換位置

sed 's/(^[a-zA-Z])([^a-zA-Z].)([^a-zA-Z])([a-zA-Z]*$)/\4\2\3\1/g' test.txt

分為4段:

第一行:root:x:0:0:root:/root:/bin/bash

root :x:0:0:root:/root:/bin / bash

11、把test.txt中出現的第一個數字和最後一個單詞替換位置

sed 's#([^0-9][^0-9])([0-9][0-9])([^0-9].)([^a-zA-Z])([a-zA-Z][a-zA-Z]$)#\1\5\3\4\2#' test.txt

12、把test.txt 中第一個數字移動到行末尾

sed 's#([^0-9][^0-9])([0-9][0-9])([^0-9].*$)#\1\3\2#' test.txt

13、在test.txt 20行到末行最前面加 ‘aaa:’

sed '20,$s/^.*$/aaa:&/' test.txt

14、列印1,100行,含有abc的行列印

sed -n '1,100{/abc/p}' 1.txt

本文轉自 iekegz 51CTO部落格,原文連結:http://blog.51cto.com/jacksoner/2043864,如需轉載請自行聯系原作者