I am very confused about when I should use ‘\’.
Consider the examples:
(1)
$ grep -Eh '^(bz|gz|zip)' filenames.txt
it matches for result that start with either bz , gz, or zip.
(2)
$ echo "(555) 123-4567" | grep -E '^\(?[0-9][0-9][0-9]\)? [0-9] [0-9][0-9]$'
output: (555) 123-4567
- With example (1) , why doesn’t it require ‘\’ for escaping parentheses ()
- With example (2) , why does it require ‘\’ for escaping ()?
I am using Ubuntu distro.
The parentheses in each of your examples mean different things.
In the first example, the parentheses are grouping and are not matched against the filenames. So you find files that start with
bzand not(bz.In your second example, the parentheses are literal and actually appear in the phone number you’re matching against.