题目要求:将命令和执行结果输出到题目下
把/etc/passwd 复制到/root/test.txt,
1、用sed打印所有行
[root@gaozhu tmp]# sed -n 'p' test.txt
2、打印test.txt的3到10行
[root@gaozhu tmp]# sed -n '3,10 p' test.txt
3、打印test.txt 中包含 ‘root’ 的行
[root@gaozhu tmp]# sed -n '/root/p' test.txt
4、删除test.txt 的15行以及以后所有行
[root@gaozhu tmp]# sed -i '15,$ d' test.txt
5、删除test.txt中包含 ‘bash’ 的行
[root@gaozhu tmp]# sed -i '/bash/d' test.txt
6、替换test.txt 中 ‘root’ 为 ‘toor’
[root@gaozhu tmp]# sed -i 's#root#toor#g' test.txt
7、替换test.txt中 ‘/sbin/nologin’ 为 ‘/bin/login’
[root@gaozhu tmp]# sed -i 's#/sbin/nologin#/bin/login#g' test.txt
8、删除test.txt中5到10行中所有的数字
[root@gaozhu tmp]# sed -nr '5,10 s#[0-9]+##gp' test.txt
8.1 拿出test.txt中5到10行中所有的数字
[root@gaozhu tmp]# sed -nr '5,10 s#.*x:([0-9]+):([0-9]+).*#\1 \2#gp' test.txt
9、删除test.txt 中所有特殊字符(除了数字以及大小写字母)
[root@gaozhu tmp]# sed -nr 's#[:/]+##gp' test.txt
10、把test.txt 中第一个数字移动到行末尾
[root@gaozhu tmp]# sed -nr 's#(.*x:)([0-9]+)(.*)#\1\3\2#gp' test.txt
11、在test.txt 20行到末行最前面加 ‘aaa:’
[root@gaozhu tmp]# sed -n '20,$s#^#aaa#gp' test.txt
12、打印奇数行(多种方法)
[root@gaozhu tmp]# sed -n '1~2p' test.txt
13、打印偶数行(多种方法)
[root@gaozhu tmp]# sed -n '2~2p' test.txt
14、将3行内容替换为Hello,This is test for sed command!,并将结果保存至指定的文件中,文件名自定义。
[root@gaozhu tmp]# sed '3s#.*#hello this is test for sed command!#gw /tmp/sed.txt' test.txt
15、在第4行后添加字符串***Hello***,并将结果保存至指定的文件中,文件名自定义。
[root@gaozhu tmp]# sed '4s#$#***hello***#gw /tmp/hello.txt' test.txt
16、在nobody行前面加字符串I am,并将结果保存至指定的文件中,文件名自定义。
[root@gaozhu tmp]# sed '/^nebula/s#^#i am#gw /tmp/sed.txt' test.txt
17、使用sed将/etc/httpd/conf/httpd.conf中#NameVirtualHost *:80去掉#号,同时将最后2行的#都去掉
[root@gaozhu tmp]# sed -ri -e '/^#Listen.*:80/s#(\#)(.*)#\2#g' -e '352,353s#(\#)(.*)#\2#g' httpd
18、把test.txt中第一个单词和最后一个单词调换位置
[root@gaozhu tmp]# sed -nr 's#([a-z]+)(:x.*)/([a-z]+)$#\3\2/\1#gp' test.txt
19、把test.txt中出现的第一个数字和最后一个单词替换位置
[root@gaozhu tmp]# sed -nr 's#(.*x:)([0-9]+)(.*)/([a-z]+)$#\1\4\3\2#gp' test.txt