10.2. sed练习题测试

(1) 把/etc/passwd复制到/root/test.txt,用sed打印所有行。
/bin/cp /etc/passwd  /root/test.txt ;  sed -n '1,$'p test.txt


(2) 打印test.txt的第3-10行。
sed -n '3,10'p 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 '5,10s/[0-9]//g' test.txt



(9) 删除test.txt中所有的特殊字符(除了数字以及大小写字母)。
 sed 's/[^0-9a-zA-Z]//g' test.txt




(10) 把test.txt中第一个单词和最后一个单词调换位置。
sed -r 's/(^[a-zA-Z]+)([^a-zA-Z].*[^a-zA-Z])([a-zA-Z]+$)/\3\2\1/' test.txt



(11) 把test.txt中出现的第一组数字(1个或多个)和最后一个单词调换位置。
sed -r 's/(^[^0-9]*)([0-9]+)([^0-9].*[^a-zA-Z])([a-zA-Z]+$)/\1\4\3\2/' test.txt


(12) 把test.txt中第一个数字移动到本行末尾。
sed -r 's/(^[^0-9]*)([0-9]+)([^0-9].*$)/\1\3\2/' test.txt



(13) 在test.txt第20行到最后一行最前面加“aaa:”。
sed '20,$s/^.*$/aaa:&/' test.txt