【问题标题】:grep in a directory and return just 1 result for each file in Unix Shell scriptinggrep 在一个目录中并为 Unix Shell 脚本中的每个文件只返回 1 个结果
【发布时间】:2025-12-16 07:10:01
【问题描述】:

我试图 grep 进入一个有几个文件的目录,我试图通过 IP 地址 grep,我的问题是,在一个文件中,IP 地址至少重复 3 或 4 次,并且我只想得到 1 个结果并继续使用另一个文件中的 grep

这就是我正在尝试做的事情,但我没有任何运气。

grep 10.01.10.0 log/MY_DIRECTORY_FILES* | sort -t . -k 2 | head -1

这只是返回 1 个结果。

【问题讨论】:

  • 您需要实际匹配吗?或者文件中的匹配计数也可以吗?
  • 我会得到匹配的数量,但首先我只是确保我没有从同一个文件中得到匹配。
  • 关键是匹配的数量是你真正想要的还是你真正想要的内容。因为这可以改变事情。
  • 我想要计数,但我不想计数 1 个文件的 3 或 4 个匹配项,我只想要 1 个文件的 1 个匹配项,然后继续下一个文件,每个文件,如果它与我试图为每个文件查找的模式匹配,则计数将为 1。
  • 您只想要匹配的文件数?那为什么要排序? grep -l 10.01.10.0 log/MY_DIRECTORY_FILES* | wc -l 能得到你想要的吗?

标签: shell sorting unix scripting grep


【解决方案1】:

head -1 返回它看到的整个输入的第一行。您在排序管道的末尾有它。

所以grep 从每个文件中吐出每个匹配的行。 sort 然后对所有行进行排序并输出它们。 head 然后返回它看到的第一行。

这不是你想要的。您希望 grep 在每个文件的第一个匹配项后停止。幸运的是,这就是grep-m 选项所做的。

-m NUM, --max-count=NUM

Stop reading a file after NUM matching lines.  If the  input  is
standard  input  from a regular file, and NUM matching lines are
output, grep ensures that the standard input  is  positioned  to
just  after the last matching line before exiting, regardless of
the presence of trailing context lines.  This enables a  calling
process  to resume a search.  When grep stops after NUM matching
lines, it outputs any trailing context lines.  When  the  -c  or
--count  option  is  also  used,  grep  does  not output a count
greater than NUM.  When the -v or --invert-match option is  also
used, grep stops after outputting NUM non-matching lines.

所以你想使用:

grep -m 1 10.01.10.0 log/MY_DIRECTORY_FILES* | sort -t . -k 2

如果您的grep 版本(OpenBSD?Solaris?)没有-m 选项(并且没有任何其他等效选项),那么您必须多次运行grep

for file in log/MY_DIRECTORY_FILES*; do
    grep 10.01.10.0 "$file" | head -n 1
done | sort -t . -k 2

为了避免运行grep N 次,您也可以使用类似这样的东西(使用gawk):

awk '/10.01.10.0/ {print; nextfile}' log/MY_DIRECTORY_FILES*

对于非gawk,您需要更多类似的东西(未经测试):

awk '!f && /10.01.10.0/ {print; f=1; next} oARGIND != ARGIND {f=0; oARGIND=ARGIND}' log/MY_DIRECTORY_FILES*

【讨论】:

  • 不幸的是,我尝试了该选项,但出现错误,我只有这些选项 grep -b, -c, -h, -i, -l, -n, -s, -v, w
【解决方案2】:

感谢 Etan Reisen 这是他的解决方案,对我有用!

grep -l 10.01.10.0 日志/MY_DIRECTORY_FILES* | wc -l

我使用 grep -l 10.01.10.0 log/MY_DIRECTORY_FILES* 验证,只显示 1 个结果。

谢谢

【讨论】:

    最近更新 更多