Home  /  Resources & support  /  FAQs  /  Backslashes and macros
Note: This FAQ is based on a question and answer that appeared on Statalist.

How do I assign multiple backslash characters to macros in Stata?

Title   Backslashes and macros
Author Alan Riley, StataCorp


Any explanations out there for the following behavior? Stata seems to run into trouble assigning multiple backslash characters to macros:

. local x1  "\"

. local x2  "\\"

. local x3  "\\\"

. local x4  "\\\\" ...

. di "[`x1']" [\]

. di "[`x2']" [\]

. di "[`x3']" [\\]

. di "[`x4']" [\\]


This behavior is by design. The backslash character is an escape character for certain other characters.

It is sometimes necessary to prevent macro substitution. If you want to display a macro rather than its contents, you might want to write something like

        . display "$myfile"

in the case of a global macro or

        . display "`myfile'"

in the case of a local macro. Of course, this won’t work, as Stata will immediately substitute the value of the “myfile” global or local macro and display that instead.

Stata allows you to use the backslash as a protection or “escape” character to prevent macro substitution or to allow delayed macro substitution.

In the examples above, the proper syntax would be

        . display "\$myfile"                  . display "\`myfile'"

to literally display

        $myfile                               `myfile'

This leads to another issue. What if a user really wishes to have a backslash in a command and still have a macro expanded after it? For example,

        . use c:\data\`myfile'

Because the backslash is an escape character and prevents macro substitution, Stata will literally try to read a file named c:\data'myfile'. Therefore, the escape character must also be able to escape itself—to tell Stata not to have it escape the opening macro character that might follow:

        . use c:\data\\`myfile'
Technical Note:   An alternative is to use forward slashes (/) when writing paths. Stata will interpret the forward slash correctly as a path delimiter. For example, you could type
        . use c:/data/`myfile'
and avoid the problem altogether.

Stata’s rules on this protection are simple and consistent:

Anywhere this is typed Stata sees this
\$ $
\` `
\\ \
\ \ (after applying the rules above)

This is why, in the examples above, every set of two backslashes “collapsed” into a single backslash.