FreezeJ' Blog

linux三剑客之grep

2022-07-01

记录grep命令常用参数用法

常用参数

递归查找所有文件

grep -r test ./  # -r递归不包含链接文件
grep -R test ./  # -R递归包含链接文件

匹配单词

grep -w test ./test.txt

匹配行

grep -x "this is a test" ./test.txt

排除匹配内容

grep -v test ./test.txt

使用正则表达式

grep -E "test$" ./test.txt

仅显示匹配部分

grep -oE "t.*t" ./test.txt

不显示任何结果

通常用于判断结果,使用$?获取是否过滤到数据。

grep -q test ./test.txt

显示匹配行号

grep -n test ./test.txt

不区分大小写

grep -i test ./test.txt

仅显示文件名

grep -l test /data/*  # 显示匹配test的文件名
grep -L test /data/*  # 显示没有匹配test的文件名

完整参数用法请参考man,不过多赘述

常见用例

排除空行

grep -Ev '^$' ./test.txt

排除空字符行

grep -xvE '\s*' ./test.txt
Tags: Linux