2

In a Windows Server environment, having trouble with escaping quotes that are within quotes. Using the functioning batch code below as a base:

awk -F "|" "$4 ~ /JUVENILE/ {sum +=$6} END {printf sum}" sourcedata.file

Problems occur when trying to include "%.3f" to printf. I am confused and unable to properly escape these quotes in my environment.

awk -F "|" "$4 ~ /JUVENILE/ {sum +=$6} END {printf """%.3f""", sum}" sourcedata.file

The above will work at the command prompt, but will not work in a simple batch file. I have also attempted to replace "%.3f" with \"%.3f\" and \""%.3f\"" and these also do not work in a batch file.

codeforester
  • 39,467
  • 16
  • 112
  • 140
  • 1
    I have forgotten Windows quoting, but in Unix you can use `'` on the outside of the program and then freely use `"` inside the script. Try this. So your script becomes `'$4 ~ /JUVENILE/ {sum +=$6} END {printf "%.3f", sum}'` – dawg Aug 21 '18 at 14:44
  • If you include the arguments in the batch file or on the command line you will need to double the percent symbol because it is used for variable expansion. – Squashman Aug 21 '18 at 14:56
  • You could use single quotes here: `awk -F '|' '$4 ~ /JUVENILE/ {sum +=$6} END {printf "%.3f", sum} sourcedata.file`. See [Difference between single and double quotes in awk](https://stackoverflow.com/q/44445852/6862601). Just realized @dawg said this as well. ` – codeforester Aug 21 '18 at 15:12
  • 1
    Folks - the OP is on Windows, not UNIX, so she's stuck with using double quotes for a command-line script. – Ed Morton Aug 21 '18 at 15:18
  • 1
    The quotation should not be the problem, but the `%` sign which needs to be doubled in a batch file... if quotation does cause trouble, have you tried `'%.3f'`? – aschipfl Aug 21 '18 at 16:00
  • It was in fact the single percent symbol, and not the neighboring quote, causing this error. Changed that snippet to `{printf \"%%.3f\", sum}`. Thanks @Squashman @aschipfl – LincolnLogger Aug 21 '18 at 19:58

1 Answers1

1

The standard advice for Windows to avoid their nightmarish quoting rules is:

a) Don't call the script from Windows. Install cygwin or similar to get a UNIX-like environment and then call the script from that, or...

b) Don't specify the script text on the command line in Windows, save it in a file instead, i.e. put this in a file named foo.awk:

BEGIN { FS="|" }
$4 ~ /JUVENILE/ {sum +=$6}
END {printf "%.3f", sum}

and then execute it as awk -f foo.awk sourcedata.file

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • 1
    My particular error, in this case, was the result of the character next to the nested quote. I have had several issues with nested quotes, and did test with this methodology with success. Will use in the future; thanks! – LincolnLogger Aug 21 '18 at 20:03