为什么“grep [Ff]irst *.txt”与包含“First”的文件不匹配?

Why does ''grep [Ff]irst *.txt'' not match a file containing "First"?

提问人:raul 提问时间:5/9/2022 最后编辑:Charles Duffyraul 更新时间:5/9/2022 访问量:96

问:

Mendel Cooper 的“高级 Bash-Scripting 指南”中的示例...

$bash --version | head -1
GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu)
$mkdir Quoting_Experimenting
$cd Quoting_Experimenting
$echo This is the first line of file1.txt > file1.txt
$echo This is the First line of file2.txt > file2.txt
$grep [fF]irst *.txt
file1.txt:This is the first line of file1.txt
file2.txt:This is the First line of file2.txt
$touch first
$grep [fF]irst *.txt
file1.txt:This is the first line of file1.txt

为什么 grep 在首次创建后找不到 file2.txt?

Regex Bash grep glob 行情

评论

1赞 jhnc 5/9/2022
你认为这意味着什么?grep [fF]irst *.txt
5赞 glenn jackman 5/9/2022
这是 3.5.8 文件名扩展,您将发现为什么在 shell 命令中使用引号很重要。
0赞 raul 5/9/2022
我认为@jhnc意思是“在当前目录的任何文本文件中查找单词 first”或“First”。grep [fF]irst *.txt
2赞 jhnc 5/9/2022
但这不是它的意思。shell 看到一个,所以它在运行之前尝试文件名扩展[grep
1赞 anubhava 5/9/2022
这个问题可能是一个相关的问题,但不是这个问题的确切骗局。trgrep

答:

7赞 anubhava 5/9/2022 #1

您需要在 grep 命令中引用搜索模式,否则 shell 会将未引用的模式扩展为仅(由于当前目录中存在文件名):[fF]irstfirstfirst

所以使用:

grep '[fF]irst' *.txt

- 关于文件名扩展的官方 BASH 文档

根据这个文档(重点是我的):

拆分单词后,除非设置了该选项(请参阅设置内置),否则 Bash 会扫描每个单词中的字符 、 和 。如果其中一个字符出现,并且未被引用,则该单词将被视为一种模式,并替换为按字母顺序排序的文件名列表,这些文件名与模式匹配。-f‘*’‘?’‘[’

1赞 Warlei Alves 5/9/2022 #2

如果您只是在寻找与任何大小写的匹配项,而不是使用正则表达式,只需使用 ignore case 命令:

grep -i first *.txt

评论

1赞 Cyrus 5/9/2022
但是,这也符合 .firST
1赞 Warlei Alves 5/9/2022
顺便说一句,我把回答的目的说得更清楚,以避免这种误解。
2赞 glenn jackman 5/9/2022
@Warlei,你会发现大多数反对票都没有任何解释。作为一个新用户,我明白这很令人沮丧。尽量不要把它当成个人。
0赞 Warlei Alves 5/9/2022
实际上,我不是新成员,而是缺席的老成员。但是,无论如何,感谢您的善意建议。