通过applescript中的sed将文本替换为撇号文本

通过applescript中的sed将文本替换为撇号文本,sed,applescript,replace,Sed,Applescript,Replace,我有一个applescript来查找和替换一些字符串。我遇到了一个替换字符串的问题,该字符串在一段时间前包含了-,但可以通过将\放在替换属性列表中来绕过它。然而,撇号似乎更令人讨厌 使用一个撇号会被忽略(替换不包含它),使用\'会给出一个语法错误(预期为“”,但找到未知标记。)而使用\'会再次被忽略。(顺便说一句,您可以继续这样做,偶数会被忽略,不均匀的语法错误) 我尝试将实际sed命令中的撇号替换为双引号(sed“s…”而不是sed“s…”),这在命令行中起作用,但在脚本中出现语法错误(预期为

我有一个applescript来查找和替换一些字符串。我遇到了一个替换字符串的问题,该字符串在一段时间前包含了-,但可以通过将\放在替换属性列表中来绕过它。然而,撇号似乎更令人讨厌

使用一个撇号会被忽略(替换不包含它),使用\'会给出一个语法错误(预期为“”,但找到未知标记。)而使用\'会再次被忽略。(顺便说一句,您可以继续这样做,偶数会被忽略,不均匀的语法错误)

我尝试将实际sed命令中的撇号替换为双引号(sed“s…”而不是sed“s…”),这在命令行中起作用,但在脚本中出现语法错误(预期为行尾等,但找到标识符)

单引号与shell混淆,双引号与applescript混淆

我还尝试了建议的'\''和来自的''''''

获取错误类型的基本脚本:

set findList to "Thats.nice"
set replaceList to "That's nice"
set fileName to "Thats.nice.whatever"
set resultFile to do shell script "echo " & fileName & " | sed 's/" & findList & "/" & replaceList & " /'"
尝试:

或者坚持你的例子:

set findList to "Thats.nice"
set replaceList to "That's nice"

set fileName to "Thats.nice.whatever"
set resultFile to do shell script "echo " & quoted form of fileName & " | sed \"s/" & findList & "/" & replaceList & "/\""
说明: sed语句通常用单引号括起来,如下所示:

set myText to "Hello"
set xxx to do shell script "echo " & quoted form of myText & " | sed 's/ello/i/'"
set myText to "Johns script"
set xxx to do shell script "echo " & quoted form of myText & " | sed \"s/ns/n's/\""
然而,在本例中,您可以完全排除单引号

set myText to "Hello"
set xxx to do shell script "echo " & quoted form of myText & " | sed s/ello/i/"
未加引号的sed语句将在包含空格后立即分解

set myText to "Hello"
set xxx to do shell script "echo " & quoted form of myText & " | sed s/ello/i there/"
--> error "sed: 1: \"s/ello/i\": unterminated substitute in regular expression" number 1
由于单引号语句中不能包含撇号(即使转义),因此可以将sed语句用双引号括起来,如下所示:

set myText to "Hello"
set xxx to do shell script "echo " & quoted form of myText & " | sed 's/ello/i/'"
set myText to "Johns script"
set xxx to do shell script "echo " & quoted form of myText & " | sed \"s/ns/n's/\""
编辑 Lauri Ranta指出,如果查找或替换字符串包含转义双引号,则我的答案无效。她的解决方案如下:

set findList to "John's"
set replaceList to "\"Lauri's\""
set fileName to "John's script"
set resultFile to do shell script "echo " & quoted form of fileName & " | sed s/" & quoted form of findList & "/" & quoted form of replaceList & "/"

我也会使用文本项分隔符。您不必在默认范围中包含
AppleScript的
,也不必在以后不使用时将属性设置回原处

set input to "aasearch"
set text item delimiters to "search"
set ti to text items of input
set text item delimiters to "replace"
ti as text
如果模式可以包含sed可以解释的内容,那么就没有简单的方法来逃避搜索或替换模式

set input to "a[a"
set search to "[a"
set replace to "b"

do shell script "sed s/" & quoted form of search & "/" & quoted form of replace & "/g <<< " & quoted form of input
将输入设置为“a[a”
将搜索设置为“[a”
将replace设置为“b”

是否执行shell脚本“sed s/”&带引号的搜索形式&“/”&带引号的替换形式&”/g
echo'\t'
在bash被调用为sh时打印文本选项卡,但是
printf%s'\t'
shopt-u xpg\u echo;echo'\t'
,或者
您好,劳里,我不确定我是否明白。您能给出一个查找和替换示例,其中我的答案不正确吗?
findList
replaceList
在seco中不能包含双引号nd代码块。
myText
不能包含像
\t
这样的转义序列。