0

When I use [0-9] pattern to search for all numbers in a file, whether to use or not use single/double quotes around the pattern produces different outputs.

$ cat numbers
this line has 3
this line has 4
this line has 2
this line has 8
this line has 1

$ grep [0-9] numbers this line has 1

$ grep '[0-9]' numbers this line has 3 this line has 4 this line has 2 this line has 8 this line has 1

What makes the difference between [0-9] and '[0-9]'? I did a similar test with [a-z] and '[a-z]', but the results were the same unlike the previous example.

I tested it on my 16.04.7 LTS (Xenial Xerus) machine. It worked as expected when I did the same test on my Mac.

trainsushi
  • 345
  • 2
  • 5
  • Show the output of ls -l. You likely have a file with a name matching that globbing pattern. – Kusalananda Jan 17 '21 at 07:40
  • @Kusalananda Yes my bad. That was indeed the issue. Thank you – trainsushi Jan 17 '21 at 07:44
  • 1
    The question that I marked this as a duplicate of is about what happens when you forget to quote a variable. One of the things that happens when using an unquoted variable is that you invoke filename globbing. This is the part that is relevant to your question since what happens in your case is due to an unquoted filename globbing pattern. – Kusalananda Jan 17 '21 at 07:49

1 Answers1

0

I can't reproduce on Bash 5.1.4 on Arch Linux, nor indeed on Ubuntu 16.04:

$ docker run --interactive --rm --tty ubuntu:16.04 /bin/bash
# cat > numbers <<EOF
> this line has 3
> this line has 4
> this line has 2
> this line has 8
> this line has 1
> EOF
# grep [0-9] numbers
this line has 3
this line has 4
this line has 2
this line has 8
this line has 1

@Kusalananda has the right idea, you probably have a file named exactly "1" which the unquoted glob expands to before being passed to grep:

# touch 1
# grep [0-9] numbers
this line has 1

The answer: Use More Quotes™ :)

l0b0
  • 51,350