三剑客之sed初级练习题

题目要求:将命令和执行结果输出到题目下

把/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

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值