Escaping File Paths in Scripts

About Escaping File Paths        

Literal strings in Lua variables must be enclosed in quotation marks and some characters in literal string values must be escaped. The need to escape characters in a script's literal strings may e.g. arise when specifying a file path name. (For more detail on escaping of literal strings in Lua see section 3.1 (Lexical Conventions) of the Lua v. 5.4 Reference Manual)

Characters to be escaped include the backslash (\, because it is the escaping character) and the double quotes ("). Both of these characters can be relevant in file paths.

On Linux/Unix                 

Usually no escaping is necessary:

    strFileToOpen = "/home/USERNAME/Documents/notecase_tmp.txt"


On Windows                    

On Windows, the backslashes in a file path must always be escaped. For example:

    strFileToOpen = "C:\\Tmp\\notecase_tmp.txt"

But on recent versions of Windows, you may optionally use the forward slash as the path directory delimiter without escaping, just as on Unix/Linux:

  strFileToOpen = "C://Tmp/notecase_tmp.txt"


Escaping the double quotes        

If a file path contains spaces, it is usually put into quotes or double quotes on the command line of Linux/Unix or Windows:

    C:\> cd "Documents and Settings\USERNAME\My Documents"


In most cases, in a NoteCase Pro Lua script it is enough to do the same quoting when passing a file path to a scriptable program command or Lua function:

    strFileToOpen = "C:\\Documents and Settings\\USERNAME\\My Documents\\notecase_tmp.txt"
    f = io.open(strFileToOpen, "r")


However, in some cases it might be necessary, to include a quoted file path in a (quoted) string, e.g. when using os.execute() to execute a command on OS level.
The command to execute must be put into quotation marks, and the file path inside the command must also be put into quotation marks. The outer quotation marks are "native" ones on Lua level, and the inner ones, surrounding the file path, are part of the (quoted) command and thus need to be escaped:

    os.execute("type \"C:\\Documents and Settings\\USERNAME\\My Documents\\notecase_tmp.txt\"")


When using a variable to store the file path, you also need to escape the quotation marks around the actual file path, because they are surrounded by the quotation marks necessary to assign the string to the strFileToOpen variable:

    strFileToOpen = "\"C:\\Documents and Settings\\USERNAME\\My Documents\\notecase_tmp.txt\""
    os.execute("type " .. strFileToOpen)
    
    
The above os.execute() calls do the same as if you would execute on the command line:

    C:\> echo "C:\\Documents and Settings\\USERNAME\\My Documents\\notecase_tmp.txt"