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

Time:05-09

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?

CodePudding user response:

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.

CodePudding user response:

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
  • Related