cat-grep-sed应用案例

来源:互联网 发布:深圳申请软件著作权 编辑:程序博客网 时间:2024/06/05 19:51

案例:

已知文件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














0 0
原创粉丝点击