【问题标题】:grep: search once for different pattern and output to several filesgrep:搜索一次不同的模式并输出到多个文件
【发布时间】:2015-12-09 16:33:03
【问题描述】:

是否可以告诉 grep 为每种匹配的搜索字符串使用不同的输出文件?

我需要递归搜索所有 *.log 以找到所有“[ERROR]”、“[WARN]”和“[ASSERT]”。但我想让它在不同的输出文件中分开。每个搜索字符串都有一个输出文件。 (无需多次调用 grep!)

搜索已经有效:(从 gmake 调用)

grep -nHr --include=*.log -e '\[ERROR\]' -e '\[WARN\]' -e '\[ASSERT\]' $(root_path) > $(root_path)/result.txt

但由于性能原因,我不想多次调用 grep:

grep -nHr --include=*.log -e '\[ERROR\]' $(root_path) > $(root_path)/result_[ERROR].txt

grep -nHr --include=*.log -e '\[WARN\]' $(root_path) > $(root_path)/result_[WARN].txt

是否有可能以某种方式拥有它:

grep -nHr --include=*.log -e {'PATTERN1' | 'PATTERN2' | 'PATTERN3'} $(root_path) > $(root_path)/result{'PATTERN1'|'PATTERN2'|'PATTERN3'}.txt

【问题讨论】:

    标签: bash file-io grep


    【解决方案1】:

    要在 1 遍中读取文件并写入多个 outFile,我会使用 awk

      awk '/^\[Error\]/ {print FILENAME ":" NR ":" $0 > "errorFile.txt" }
           /^\[Warn\]/ {print FILENAME ":" NR ":" $0 > "warnFile.txt" }
           /Assert/ {print FILENAME ":" NR ":" $0 > "assertFile.txt" }'  logFile
    

    如果您确定 Error/Warn/Assert 标记始终是感兴趣的行的第一个并使用行首 reg-exp 字符 (^ ),即。

    /^Error/ {print $0 > "errorFile.txt" 
    

    【讨论】:

    • 字符串“[WARN]”和“[ERROR]”确实总是在日志中的行首,但“ASSERT”字符串可能在任何地方。
    • 我喜欢 grep 的 -nH 选项: -H, --with-filename 打印每个匹配的文件名; -n, --line-number 打印带有输出行的行号
    • 这看起来很有希望,但为什么 $0 不打印整行?
    • in awk $0 根据定义是整行。如果您没有看到所有内容,则意味着您的日志中有不寻常的字符,或者信息被分成多行。无法提供帮助,因为这听起来非常不可预测。
    • 该行有 [] 和空格。喜欢:“[WARN][READBACK_HANDLER]:无法暂停计数的回读处理程序”
    【解决方案2】:
     sed -n '{
    /\[ERROR\]/w errorlog
    /\[WARN\]/w warnlog
    /\[ASSERT\]/w assertlog
    }' $(  find /your/path/here -type f -name "*.log" )
    

    可能对你有用。

    【讨论】:

    • 这会导致错误:sed: -e expression #1, char 0: unmatched `{'。
    • 我想从 makefile 中运行它,它在 find 之前的 $ 有问题: ...assertlog }' $( find / ...
    • 如果您尝试将以上所有内容放在一行中,您将收到无与伦比的{ 错误。
    • which has a problem with the $ before the find: - 此错误可能与 unmatched { 有关。正如我所做的那样,将 sed 脚本拆分为不同的行,您可能会通过。 @schwdk
    猜你喜欢
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    相关资源
    最近更新 更多