I am using Ack version 2.04, in PowerShell. I want to search texts like "jsonClass":"Page" (quotes included) inside text files.
I can't seem to get the quoting and escaping correct.
ack -c --match '"jsonClass":"Page"'
It doesn't work in PowerShell. I guess ack's picking up the single quotes as well.
Escaping the double quotes gives an invalid regex error:
ack -c --match "\"jsonClass\":\"Page\""
Invalid regex '\':
Trailing \ in regex m/\/ at C:\CHOCOL~1\lib\ACK2~1.04\content\ack.pl line 315
I tried the literal option as well, but I think ack's interpreting the colon as file parameters.
ack -c -Q --match "jsonClass":"Page"
ack.pl: :Page: No such file or directory
What am I missing?
I am using PowerShell v2.
To complement JPBlanc's effective answer with a PowerShell v3+ solution:
When invoking external programs such as ack
, use of the so-called stop-parsing symbol, --%
, makes PowerShell pass the remaining arguments through as-is, with the exception of expanding cmd.exe
-style environment-variable references such as %PATH%
:
ack --% -c --match "\"jsonClass\":\"Page\""
This allows you to focus on the escaping rules of the target program only, without worrying about the complex interplay with PowerShell's own parsing and escaping.
Thus, in PowerShell v3 or higher, the OP's own 2nd solution attempt would have worked by passing --%
as the first parameter.
See Get-Help about_Parsing
.
Note that the exact equivalent of the above command without the use of --%
(that also works in PSv2 and is generally helpful if you want to include PowerShell-expanded variables / expressions in other arguments) would look like this:
ack -c --match '"\"jsonClass\":\"Page\""'
That is, the entire argument to be passed as-is is enclosed in single quotes, which ensures that PowerShell doesn't interpret it.
Note the inner enclosing "
that aren't present in JPBlanc's answer (as of this writing). They guarantee that the argument is ultimately seen as a single argument by ack
, even if it contains whitespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With