如何在appleScript / shell中转义单引号?

时间:2016-07-24 17:37:42

标签: bash shell applescript

我看过这个话题:single quote escaping in applescript/shell虽然它很有用,但它并没有解决我的问题。此AppleScript代码段说明了此问题:

set lastName to "O'Donnell"
set lastScript to "/usr/libexec/PlistBuddy /Users/david/.name.plist -c 'Set Last '" & quoted form of (lastName & "'")
display dialog lastScript
do shell script lastScript

属性列表文件" .name.plist"在我的主文件夹中包含一个键'最后一个'存储名称' Donnell'。变量lastScript传递为:

/usr/libexec/PlistBuddy /Users/david/.name.plist -c 'Set Last ''O'\''Donnell'\'''

脚本执行,但是' Last'被设定为ODonnell'没有重要的撇号。这可以通过在shell中运行此命令来证明:

/usr/libexec/PlistBuddy /Users/david/.name.plist -c 'Print Last'

PlistBuddy可以以交互模式运行:

/usr/libexec/PlistBuddy /Users/david/.name.plist

命令:

'Set Last O\'Donnell' 

成功保存名称。我做错了什么?

1 个答案:

答案 0 :(得分:1)

你的逃跑搞砸了。将文本值放在双引号中以保持PlistBuddy满意,然后单引引整个-c参数以保持bash满意:

to escapeDoubleQuotes(txt)
  set AppleScript's text item delimiters to "\\"
  set lst to txt's text items
  set AppleScript's text item delimiters to "\\\\"
  set txt to lst as text
  set AppleScript's text item delimiters to "\""
  set lst to txt's text items
  set AppleScript's text item delimiters to "\\\""
  return lst as text
end escapeDoubleQuotes

set lastName to "O'Donnell"

"/usr/libexec/PlistBuddy /Users/david/.name.plist -c " & quoted form of ("Set Last " & escapeDoubleQuotes(lastName))

--> "/usr/libexec/PlistBuddy /Users/david/.name.plist -c 'Set Last \"O'\\''Donnell\"'"