欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

cat-grep-sed应用案例

发布时间:2025/3/11 编程问答 36 豆豆
生活随笔 收集整理的这篇文章主要介绍了 cat-grep-sed应用案例 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

案例:

已知文件test.txt内容为:

test

liming

xiaoming

请打印出test.txt内容时,不包含xiaoming字符串的命令。


创建文件test.txt

[root@hello110 testdata]# cat >>test.txt<<EOF
> test
> liming
> xiaoming
> EOF


实现

方法一:用head命令

[root@hello110 testdata]# head -2 test.txt 
test
liming


head命令:取头部的前n行。如果不接参数,默认是前10行。

命令:head -2 test.txt 或 head -n 2 test.txt


方法二:grep

grep命令:过滤器,把想要的或者不想要的分离开

想要什么:grep "要的内容"

不想要什么:grep -v "不想要的内容"

[root@hello110 testdata]# grep "liming" test.txt 
liming
[root@hello110 testdata]# grep -v "liming" test.txt 
test
xiaoming


grep画蛇添足的用法:

[root@hello110 testdata]# cat test.txt |grep -v "liming" test.txt 
test
xiaoming

不专业!


方法三:sed

sed:过滤。格式:sed [-n]  '/过滤的内容/处理的命令'  文件

-n:取消sed的默认输出

-i:改变文件内容

处理命令:有很多。p  print。d  delete,不删除内容。

[root@hello110 testdata]# sed '/liming/d' test.txt  
test
xiaoming
[root@hello110 testdata]# cat test.txt             
test
liming
xiaoming

[root@hello110 testdata]# sed -n '/liming/p' test.txt 
liming
[root@hello110 testdata]# sed '/liming/p' test.txt    
test
liming
liming
xiaoming














总结

以上是生活随笔为你收集整理的cat-grep-sed应用案例的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。