如何在 Linux 系统中使用 grep 命令搜索不带文件名的字符串?

linuxoperating systemopen source

我们知道可以使用 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 文档,-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

相关文章


有用资源