Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape double quotes and colon in ACK in PowerShell

Tags:

powershell

ack

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.

like image 210
sas1138 Avatar asked Dec 18 '22 12:12

sas1138


1 Answers

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.

like image 189
mklement0 Avatar answered Jan 05 '23 15:01

mklement0