wonder
wonder

Reputation: 33

How to pass a single quote (') into a batch script?

Hello and thanks for the help.

I'm having difficulty escaping the single quote character (') in a Windows Batch script. I've tried ^', \', ''', '\'', and so on. Online searches haven't solved it either. I'm stumped.

This script uses cgywin64 gawk to format a list of folders:

@echo off
du -sk ./*  | sort -nr | head -40 | gawk '{printf("%%^'14d kB %%s %%s %%s %%s %%s %%s %%s %%s\n", $1, $2, $3, $4, $5, $6, $7, $8, $9)}'

When run, it gives me the following errors:

gawk: cmd. line:1: {printf("%^14d
gawk: cmd. line:1:         ^ unterminated string
gawk: cmd. line:1: {printf("%^14d
gawk: cmd. line:1:         ^ syntax error

Without doing any character escaping, the gawk command would look something like:

gawk '{printf("%'14d kB %s %s %s %s %s %s %s %s\n", $1, $2, $3, $4, $5, $6, $7, $8, $9)}'

The format string at the beginning (%'14d) tells gawk to use commas when printing the integer ("123456789" prints as "123,456,789"). This string has a single quote ('), which I can't figure out how to pass into the batch script without errors.

So how do I pass a single quote (') into a batch script?

Any help appreciated.

Upvotes: 1

Views: 2320

Answers (1)

Compo
Compo

Reputation: 38709

The following advice is untested, and is currently based on my limited understanding.

gAwk uses single quotes for quoting in POSIX-compliant, Bourne-style shells of which cmd.exe isn't one.

With cmd.exe those single quotes used for quoting, ', need to be replaced by double quotes, ".

The single quote not used for quoting, %'14d, does not require special attention by gAwk because characters within double quotes are protected.

In cmd.exe single quotes are not problematic, so this character can remain untouched.

So in cmd.exe you need to replace the surrounding single quotes '{ and }' with double quotes "{ and }".

Then you have to escape the internal double quotes to prevent cmd.exe from closing the opening one, "{, prematurely.

In cmd.exe a double quote is usually escaped by preceding it with a backslash, \".

Your command in cmd.exe would therefore look like this:

du -sk ./*  | sort -nr | head -40 | gawk "{printf(\"%'14d kB %s %s %s %s %s %s %s %s\n\", $1, $2, $3, $4, $5, $6, $7, $8, $9)}"

The advice above is for cmd.exe; however when running from a batch file there is an additional gotcha.

All percent characters require doubling! % becomes %%.

So given all of the above, remembering that this is completely untested, your command in a batch file would be:

du -sk ./*  | sort -nr | head -40 | gawk "{printf(\"%%'14d kB %%s %%s %%s %%s %%s %%s %%s %%s\n\", $1, $2, $3, $4, $5, $6, $7, $8, $9)}"

Upvotes: 1

Related Questions