gilzero
gilzero

Reputation: 1902

Confusing about when to (not to) use backslash '\' for escaping

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


  1. With example (1) , why doesn't it require '\' for escaping parentheses ()
  2. With example (2) , why does it require '\' for escaping ()?

I am using Ubuntu distro.

Upvotes: 0

Views: 61

Answers (1)

Greg Hewgill
Greg Hewgill

Reputation: 993611

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 bz and not (bz.

In your second example, the parentheses are literal and actually appear in the phone number you're matching against.

Upvotes: 4

Related Questions