我有一个命令发送到stdout一系列数字,每个数字都在一个新行上。我需要确定列表中是否存在特定数字。匹配需要是精确的,而不是一个子集。例如,解决此问题的一种简单方法是:
/run/command/outputing/numbers | grep -c <numberToSearch>
Run Code Online (Sandbox Code Playgroud)
在搜索“456”时,我的版本在以下列表中给出了误报:
1234567
98765
23
1771
Run Code Online (Sandbox Code Playgroud)
如果计数不为零,则发现匹配;如果计数为零,则该数字不在列表中。
这样做的问题是 numberToSearch 可以匹配一行上的数字子序列,而不是我只想要整行上的命中。我查看了 grep 的手册页,并没有看到任何只能匹配整行的方法。有没有办法做到这一点,或者我最好使用awk或sed或其他工具代替?我需要一个关于正在搜索的数字是否存在的二进制答案。
来自 GNU grep 手册:
`-x'
`--line-regexp'
Select only those matches that exactly match the whole line.
(`-x' is specified by POSIX.)
Run Code Online (Sandbox Code Playgroud)
所以:
/run/command/outputing/numbers | grep -x <numberToSearch>
Run Code Online (Sandbox Code Playgroud)
将为您提供全线匹配:
/run/command/outputing/numbers | grep -cx <numberToSearch>
Run Code Online (Sandbox Code Playgroud)
将为您提供全线匹配的数量。