如何在 Linux 中 grep 没有文件名的字符串?

我们知道我们可以使用 grep 命令在一个文件或多个文件的所有行中搜索特定的字符模式。grep 命令对文件中的单词执行不区分大小写的搜索。

让我们看一个简单的例子,我们将在一个目录中存在的所有文件中 grep 一个模式。

命令

grep -i ‘lp’ Sample*
输出结果
Sample: The sample was printed via the internet.
Sample: I believe lp cares about what the device is.
Sample1: This was printed via the internet.
Sample1: I believe lp cares about what the device is.
Sample2: This was printed via the internet.
Sample3: I believe lp cares about what the device is.

这个特定场景的唯一问题是我们不希望文件名与输出一起打印。我们只需要找到特定模式的字符串,我们只需要打印该字符串。

在这种情况下,我们可以使用-h参数来隐藏文件名。

命令

grep -i -hn ‘lp’ Sample*

根据 Linux Docs, -h 标志执行以下操作,

“-h, --no-filename

禁止输出文件名的前缀。当只有一个文件(或只有标准输入)要搜索时,这是默认设置。”

输出结果

The sample was printed via the internet.
I Believe lp cares about what the device is.
This was printed via the internet.
I believe lp cares about what the device is.
This was printed via the internet.
I believe lp doesn't care what the device is