grep

命令常见用法

在文件中搜索一个单词,命令会返回一个包含“match_pattern”的文本行:

grep match_pattern file_name
grep "match_pattern" file_name

grep -C 5 "match_pattern" file            # 显示file文件里匹配foo字串那行以及上下5行
grep -B 5 "match_pattern" file            # 显示foo及前5行
grep -A 5 "match_pattern" file            # 显示foo及后5行

在多个文件中查找:

grep "match_pattern" file_1 file_2 file_3 ...s

标记匹配颜色 –color=auto 选项:

grep "match_pattern" file_name --color=auto

使用正则表达式 -E 选项:

grep -E "[1-9]+"
或
egrep "[1-9]+"

递归搜索文件

在多级目录中对文本进行递归搜索:

# . 表示当前目录。 -n 在显示符合范本样式的那一列之前,标示出该列的编号。
grep "text" . -r -n

Linux grep 命令用于查找文件里符合条件的字符串。

# 以递归的方式查找 “etc/acpi” 文件及文件夹
grep 'test msg' /etc/acpi -r
# 当前路径下文件及文件夹
grep 'test msg' . -r
grep 'test msg' * -r

忽略匹配样式中的字符大小写:

echo "hello world" | grep -i "HELLO"
hello

在grep搜索结果中包括或者排除指定文件:

#只在目录中所有的.php和.html文件中递归搜索字符"main()"
grep "main()" . -r --include *.{php,html}
#在搜索结果中排除所有README文件
grep "main()" . -r --exclude "README"
#在搜索结果中排除filelist文件列表里的文件
grep "main()" . -r --exclude-from filelist

grep -R --exclude-dir=node_modules --exclude-dir=build 'web-tools/template/footer' .

查看文件

    tail -n 20 access.log        # 显示 xxx 最后20行
    tail -n +20 access.log        # 显示 xxx 前面20行
    tail -f access.log        # 循环读取文件

查找文件

    find / -name nginx-log-analyser