我正在尝试 grep 到一个包含几个文件的目录,我正在尝试按 IP 地址进行 grep,我的问题是,在单个文件中,ip 地址至少重复 3 或 4 次,并且我只想得到 1 个结果并继续在另一个文件中执行 grep
这就是我正在尝试做的事情,但我没有任何运气。
grep 10.01.10.0 log/MY_DIRECTORY_FILES* | sort -t . -k 2 | head -1
这仅返回 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*
关于shell - grep 在目录中,并为 Unix Shell 脚本中的每个文件仅返回 1 个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33108487/