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