Masking Quotes in SAS OS Commands

Drop the %str(), %nrStr() and %bQuote()! Save yourself the headache by using a double-double quote.

OS Commands and Quotes

When you’re passing commands to the OS from SAS, you regularly need to wrap parts of the command in quotes. This is especially true when you’re referring to a file path with spaces in it.

In my world, I’ll often also want to construct all or part of the command using macro variables. This approach makes for a really flexible way of having SAS interface with the OS.

The issue then, is how to reliably resolve macro variables, within the quotes of our OS command. Keen macro coders will know that macro variables don’t resolve within single quotes ('), so mixing both double and single quotes is out.

Double-Double Quotes

"type '&myFilePathWithSpaces.' "

'type "&myFilePathWithSpaces." '

Neither of these two work when I pass them into a FileName Pipe, attempting to read the contents of a file whose path has spaces. We could start to mess around with macro string quoting functions, but looking up their definitions always makes me a little uneasy. Instead, I go for a double-double quote.

A double-double quote is simply two double quotes, put next to each other with no space in-between (""). To use them, wrap your whole command in one pair of double quotes first…

" type &myFilePathWithSpaces. "

…then put a double-double quote (""), wherever you want the OS to see it as one double quote (")…

" type ""&myFilePathWithSpaces."" "

I’ve added spaces around the initial pair of enclosing double quotes, to avoid confusion. They aren’t strictly required, but removing them makes the end of this command look strange, with 3 double quotes next to each other.

"type ""&myFilePathWithSpaces."""

I use the above whenever I need to send an OS command through SAS, even if the resolved macro variable doesn’t usually contain spaces. It’s so easy to mask for them in this way, that I might as well do it anyway!