gpt4 book ai didi

sed - 在applescript中通过sed用撇号文本替换文本

转载 作者:行者123 更新时间:2023-12-02 20:39:40 27 4
gpt4 key购买 nike

我有一个苹果脚本来查找和替换多个字符串。我之前遇到过一个包含 & 的替换字符串的问题,但可以通过将\& 放在替换属性列表中来解决它。然而撇号似乎更烦人。

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

我尝试用双引号替换实际 sed 命令中的撇号(sed "s..."而不是 sed 's...'),这在命令行中有效,但在脚本中给出了语法错误(Expected end of行等,但找到了标识符。)

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

我也按照建议尝试了“\”here和来自 here 的 '"'"' .

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

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

关于sed - 在applescript中通过sed用撇号文本替换文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12772757/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com