简体   繁体   中英

How to include double quote in Matlab's system() command

I need to pass filename as input to a powershell command which includes spaces. Hence I am hoping to include double quotes.

However, Matlab "eats" all double quotes in the input of system() when passing arguments to powershell.

For example, note how the examples below all the the same output.

>> system('powershell.exe echo a c','-echo')
a 
c 
ans =
     0
>> system('powershell.exe echo "a c"','-echo')
a 
c 
ans =
     0
>> system('powershell.exe echo ""a c""','-echo')
a 
c 
ans =
     0
>> system(['powershell.exe echo ',char(34),'a c',char(34)],'-echo')
a 
c 
ans =
     0

The actual output for echo "ac" in powershell is a c in a single line. The change of line only occurs without double quotes.

Just for experiment, I also tried ""ac"" and the expected input is the same as change line, a, change line, c. With the return, it seems that any and all double quotes are "eaten" alive by Matlab.

How do I bring the double quotes back when using system() ?

It is PowerShell that is eating your double quotes:

  • You're passing a command (piece of PowerShell code) to the PowerShell CLI , via the -Command ( -c ) parameter (which is positionally implied in your case).

  • " characters that should be considered part of the command must be escaped as \" (sic)

    • The reason that unescaped " don't work is that PowerShell considers them to have syntactic function on the command line only - they are simply stripped after all arguments have been parsed; the resulting tokens are then joined with spaces, and the resulting string finally interpreted as PowerShell code.
  • While using just \" in your command would fix the problem, it is advisable to also enclose the entire command being passed in "..." , because that prevents potentially unwanted whitespace normalization .

system('powershell.exe " echo \"a c\" "', '-echo')

Caveat :

  • Since MatLab's system() function executes the given command line via cmd.exe (which is inefficient in your case, since you don't need shell functionality), use of \" can break the invocation, due to how cmd.exe 's parses command lines.

  • To avoid edge cases when cmd.exe is involved , enclose the overall command in "...." and escape pass-through " as follows:

    • Use "^"" (sic) when calling powershell.exe (the Windows PowerShell CLI)
    • Use "" when calling pwsh.exe (the PowerShell (Core) 7+ CLI).
    • See this answer for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM