为什么'' grep [ff] irst *.txt''不匹配包含“首先”的文件?

发布于 2025-01-27 15:13:12 字数 552 浏览 4 评论 0原文

孟德尔·库珀(Mendel Cooper)的“高级bash施法指南”中的示例...

$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?

Example from Mendel Cooper's "Advanced Bash-Scripting Guide"...

$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

Why does grep not find file2.txt after first has been created?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小忆控 2025-02-03 15:13:12

您需要在grep命令中引用搜索模式,否则shell扩展了未引用的模式 [ff] irst to holly first仅(由于文件名首先存在于当前目录中):

请使用:

grep '[fF]irst' *.txt

- 根据该文档的官方狂欢文件

(重点是我的):

单词拆分后,除非设置了-f选项(请参阅set indendin),请bash扫描每个单词的字符'*'*''?',<代码>'['。如果这些字符之一出现,并且是未引用,则该单词被视为模式,并用字母排序的文件名匹配图案。


You need to quote the search pattern in grep command otherwise shell expands unquoted pattern [fF]irst to first only (due to filename first being present in your current directory):

So use:

grep '[fF]irst' *.txt

- Official BASH documentation on filename expansion

As per this doc (emphasis is mine):

After word splitting, unless the -f option has been set (see The Set Builtin), Bash scans each word for the characters ‘*’, ‘?’, and ‘[’. If one of these characters appears, and is not quoted, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of filenames matching the pattern.

星星的軌跡 2025-02-03 15:13:12

如果您只是在寻找任何情况下的匹配项,而不是使用正则态度,只需使用ighore case命令:

grep -i first *.txt

If you're simply looking for a match with any case, instead of using a regex, just use the ignore case command:

grep -i first *.txt
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文