提问人:raul 提问时间:5/9/2022 最后编辑:Charles Duffyraul 更新时间:5/9/2022 访问量:96
为什么“grep [Ff]irst *.txt”与包含“First”的文件不匹配?
Why does ''grep [Ff]irst *.txt'' not match a file containing "First"?
问:
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?
答:
7赞
anubhava
5/9/2022
#1
您需要在 grep 命令中引用搜索模式,否则 shell 会将未引用的模式扩展为仅(由于当前目录中存在文件名):[fF]irst
first
first
所以使用:
grep '[fF]irst' *.txt
根据这个文档(重点是我的):
拆分单词后,除非设置了该选项(请参阅设置内置),否则 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
实际上,我不是新成员,而是缺席的老成员。但是,无论如何,感谢您的善意建议。
评论
grep [fF]irst *.txt
grep [fF]irst *.txt
[
grep
tr
grep