Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 958
raul Avatar asked Oct 20 '25 12:10

raul


2 Answers

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.

like image 161
anubhava Avatar answered Oct 23 '25 00:10

anubhava


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
like image 33
Warlei Alves Avatar answered Oct 23 '25 02:10

Warlei Alves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!