首页 > 解决方案 > 如何使用 bash 在单行上查找只有模式的文本文件

问题描述

我正在尝试使用 bash 查找仅在文件的 1 行上包含特定模式的文本文件。

例如,我有以下文本文件:

1234123 123412341 0000 23423 23422
121231 123123 12312 12312 1231
567 567 43 234 12
0000
929 020 040 040 0000

该文件包含一行(第 4 行),它专门具有 pattern 0000。但是,我尝试过ls | grep 0000,它还返回模式位于文件其他位置的文件,而不必在一行上“单独”。

如何使用 bash 找到仅存在于文件单行中的模式?

标签: bashgrep

解决方案


Assuming we have four input files:

$ head file*
==> file1 <==
0000
0000

==> file2 <==
abcd
0000
abcd

==> file3 <==
0000x

==> file4 <==
abcd

file4 doesn't contain the pattern at all, file3 contains the pattern, but it's not on a line on its own, file1 has multiple lines that contain just the pattern, and file2 has exactly one line with just the pattern.

To get all files that contain the pattern anywhere:

$ grep -l '0000' file*
file1
file2
file3

To get all files that contain lines with nothing but the pattern:

$ grep -lx '0000' file*
file1
file2

And if you wanted only files that contain exactly one line with nothing but the pattern, you could use -c to get a count first:

$ grep -xc '0000' file*
file1:2
file2:1
file3:0
file4:0

and then use awk to print only the files with exactly one match:

$ grep -xc '0000' file* | awk -F: '$2==1 {print $1}'
file2

With GNU awk, you could also do this directly:

$ awk 'BEGINFILE {c=0} /^0000$/ {++c} ENDFILE {if (c==1) print FILENAME}' file*
file2

推荐阅读