用applescript中的sed替换带有撇号文本的文本

时间:2012-10-07 20:51:06

标签: sed applescript replace

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

使用单个撇号只会被忽略(替换不包含它),使用\'会出现语法错误(预期“”“但发现未知令牌。)并且使用\”会再次被忽略。(你可以继续btw,偶数被忽略不均匀得到语法错误)

我尝试用双引号替换实际sed命令中的撇号(sed“s ...而不是sed's ...”),这在命令行中有效,但在脚本中出现语法错误(预期结束时)线等,但找​​到了标识符。)

单引号混淆了shell,带引号的双引号。

我也尝试了来自herehere和'''''的'\''。

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

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 & " /'"

2 个答案:

答案 0 :(得分: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/\""

EDIT 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 & "/"

答案 1 :(得分: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