How can I search for (escape) a dollar sign using ack?
Asked Answered
D

4

7

I want to ack for the literal string: "$$" in a code base, but escaping the dollar sign like this:

ack \$\$

doesn't work.

Dearborn answered 21/2, 2013 at 20:26 Comment(1)
ack '[$][$]' . Character class. Cleaner than N escapes.Carver
A
18

You are getting confused by shell quoting. When you type:

ack "\\\$\\\$\("

the shell interpolates the double quoted string so that \\ is translated to \, \$ is translated to $ and \( is translated to \( and ack gets the string \$\$\( as its argument. It is much simpler to avoid the shell interpolation by using single quotes and invoke:

ack '\$\$\('

Replace ack with echo to explore how the shell is expanding the strings. Note that

ack "\\$\\$\("

will also work, but for slightly different reasons. Here, the first two \ are treated as a single (escaped) \, then the $ is translated as a $ because it is followed by a character that is not a valid character in a variable name. \( expands to \( instead of simply ( because ( is not subject to interpolation and therefore does not need to be escaped. But note that outside of double quotes, \( is converted to (.

Shell quoting rules get confusing sometimes!

Abbey answered 21/2, 2013 at 20:47 Comment(1)
yeah i get confused by shell quoting rules easily - the echo trick is a great idea though, thanks for sharingDearborn
A
17

Use ack's -Q to do your escaping.

ack -Q '$$'
Arbuthnot answered 16/5, 2013 at 17:22 Comment(0)
D
1

You can escape the dollar sign character with three backslashes, like this:

ack "\\\$\\\$"

or use single quotes, where you only have to escape it once:

ack '\$\$'
Dearborn answered 21/2, 2013 at 20:27 Comment(1)
It's much easier to use single quotes: ack '\$\$\(' should work just fine.Abbey
L
0

You can use printf to take care of the quoting for you by using the %q format specifier.

$ printf %q '$$('
\$\$\(

help print has the following to say (I'm assuming bash here)`

 %q quote the argument in a way that can be reused as shell input
Lye answered 21/2, 2013 at 20:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.