从目录中,我需要找到所有包含十进制数字(例如42.7)和关键字“foo”或“goo”的文件。我该如何实现?
假设我有一个包含三个文件的目录
file1.txt
=======
double x = 2.7
foo();
file2.txt
===========
double u = 5.7
file3.txt
===========
goo(42.0);
搜索命令应提供file1.txt和file3.txt。什么是搜索命令来实现这一目标?我搜索了解决方案,但我所能找到的全部解决方案是使模式同时出现在同一行中。我也很难处理小数点。
最佳答案
使用2个grep -l
命令列出包含正则表达式的文件名(而不是匹配的行)。通过xargs
连接它们,例如:
grep -Pl '(\d+[.]?\d*|\d*[.]?\d+)' file?.txt | xargs grep -Pl '(foo|goo)'
例:创建输入文件。除了问题中列出的示例以外,我还使用其他一些示例来说明找到的模式/文件:
cat > file1.txt <<EOF
double x = 2.7
foo();
EOF
cat > file2.txt <<EOF
double u = 5.7
EOF
cat > file3.txt <<EOF
goo(42.0);
EOF
cat > file4.txt <<EOF
foo(4);
EOF
cat > file5.txt <<EOF
goo(.42);
EOF
cat > file6.txt <<EOF
goo(.);
EOF
运行grep -l ... | xargs grep -l ...
查找匹配的文件:grep -Pl '(\d+[.]?\d*|\d*[.]?\d+)' file?.txt | xargs grep -Pl '(foo|goo)'
打印品:file1.txt
file3.txt
file4.txt
file5.txt
在这里,grep
使用以下选项:-P
:使用Perl正则表达式。-l
:仅列出文件名,而不列出匹配的行。正则表达式包含以下部分:
\d*
:0到9的任何数字,重复0次或更多次。\d+
:相同,重复1次或更多次。[.]
:文字点(.
)。否则,无需转义,.
表示任何字符。另请参阅:
-l
--files-with-matches
Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning of each file stops on the first match. (
-l
is specified by POSIX.)
grep
manual
关于regex - 搜索出现在同一文件中但可能不在同一行中的文件中的两个模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64244702/