您的位置:首页 > 其它

cat-grep-sed应用案例

2016-10-27 16:21 176 查看
案例:

已知文件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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: