bash - 如何使用 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 找到仅存在于文件单行中的模式?
解决方案
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
推荐阅读
- azure - Azure 上的 ElasticSearch - VM 可用性集与规模集
- python-3.x - 如何通过python中的对象方法传递元组列表
- c++ - 为什么有些程序员使用字符串作为输入然后转换它?
- haproxy - HAProxy 如何转发流量
- python - 带有色调返回错误的 seaborn kdeplot 无法将字符串转换为浮点数:“女性”
- postgresql - 如何根据当前用户将外键插入表中
- javascript - 如何在 ReactJS 中将值或字段从一个页面传递到另一个页面?
- android - 将 SDK 集成到 Flutter 应用程序中的问题
- google-sheets - Randomly splitting a dynamic range into equal groups
- javascript - clearInterval 不会停止函数