3

我有一个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 & " /'"
4

2 回答 2

1

尝试:

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/Thats.nice/That\\'s nice/\""

或坚持你的例子:

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 "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 "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 & "/"
于 2012-10-08T00:18:35.767 回答
0

我也会使用文本项目分隔符。如果以后不使用,您不必包含AppleScript's在默认范围内或将属性设置回来。

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

如果你必须使用正则表达式,像 Ruby 这样的脚本语言有从字符串创建模式的方法。

set input to "aac"
set search to "(a+)"
set replace to "\\1b"

do shell script "ruby -KUe 'print STDIN.read.chomp.gsub(Regexp.new(ARGV[0]), ARGV[1])' " & quoted form of search & " " & quoted form of replace & " <<< " & quoted form of input without altering line endings
于 2012-10-08T19:25:37.750 回答