Because "\\$"
is a string and /\\$/
is not; in strings, some of the escape characters get eaten up (like \"
to escape a double-quote within the string).
/\\$/ => regular expression: literal backslash at end-of-expression "\\$" => string: \$ => regular expression: literal dollar sign
To get behavior like the first case in a string, use "\\\\$"
.
There are other, less obvious characters which need the same attention; under-quoting or over-quoting should be avoided:
/\(test\)/ => 6 characters `(test)' "\(test\)" => /(test)/ => 4 characters `test' (with unused grouping)
An example of trying to match some diagonal compass directions:
/(N|S)(E|W)/ => `NE' or `NW' or `SE' or `SW' (correct) "(N|S)(E|W)" => /(N|S)(E|W)/ (correct) "\(N|S\)\(E|W\)" => /(N|S)(E|W)/ (correct) (NOTE: all \ had no effect) "\(N\|S\)\(E\|W\)" => /(N|S)(E|W)/ (correct) (NOTE: all \ had no effect)
/\(N|S\)\(E|W\)/ => `(N' or `S)(E' or `W)' /\(N\|S\)\(E\|W\)/ => `(N|S)(E|W)' only
There is also confusion regarding different forms of special characters; POSIX requires that `\052'
be treated as any other `*'
, even though it is written with 4 bytes instead of 1. In compatibility mode, gawk will treat it as though it were escaped , namely `\*'
.