如何在 find 和 grep 之后输出文件的行?

如何在 find 和 grep 之后输出文件的行?

您好,我想从当前日期的日志文件中输出错误消息。

首先,我搜索带有特定前缀的今天的日志:

find /home/USER/logfilesError/ -maxdepth 1 -type f -name "xy_*" -daystart -mtime -1

它给了我输出:

/home/USER/logfilesError/xy_2071.log
/home/USER/logfilesError/xy_2072.log
/home/USER/logfilesError/xy_2073.log

在这些文件中,我想搜索字符串“ERROR”:

grep -rl "ERROR" /home/USER/logfilesError/

这给了我所有包含“错误”的日志文件,不仅是从今天开始。

输出(仅部分输出):

/home/USER/logfilesError/xy_55.log
/home/USER/logfilesError/xy_1015.log

问题:

我如何将它们组合到脚本中?

日志文件中一行的语法是:

2013-11-24 06:30:30,549 [main] ERROR *(+Errormessage)*

答案1

尝试这个:

find /home/USER/logfilesError/ -maxdepth 1 -type f -name "xy_*" \
    -daystart -mtime -1 -exec grep -Hl "ERROR" "{}" +

man find

-exec command {} +
              This  variant  of the -exec action runs the specified command on
              the selected files, but the command line is built  by  appending
              each  selected file name at the end; the total number of invoca‐
              tions of the command will  be  much  less  than  the  number  of
              matched  files.   The command line is built in much the same way
              that xargs builds its command lines.  Only one instance of  `{}'
              is  allowed  within the command.  The command is executed in the
              starting directory.

相关内容