循环查看列表以查找&更换

时间:2017-04-02 21:04:10

标签: shell sed applescript repeat automator

在我的脚本中,theString通常少于200个单词。 theFindList和replaceWithList在每个中有78个术语......用于查找第一个列表中每个术语的每个出现次数,并将其替换为第二个列表中的相应术语。 脚本运行正常,但在重复循环中78个不同的do shell脚本调用中执行sed命令的速度很慢。 如果将所有内容传递给shell以便在那里完成迭代会更快。我怎么做? 这是AppleScript中现在相关的重复部分。我会把这个东西放进Automator中,所以我可以在一个"运行shell脚本"行动会起作用。我可以在一个制表符分隔数据字符串中查找和替换列表。查找和替换列表是常量,因此需要将这些列表添加到shell脚本中,并且只需要从上一个操作接收theString。

set theString to "foo 1.0 is better than foo 2.0. The fee 5 is the best."
set toFindList to {"foo", "fee", "fo", "fum"}
set replaceWith to {"bar", "bee", "bo", "bum"}
set cf to count of toFindList
-- replace each occurrence of the word followed by a space and a digit
repeat with n from 1 to cf
    set toFindThis to item n of toFindList
    set replaceWithThis to item n of replaceWithList
    set scriptText to "echo " & quoted form of theString & " | sed -e 's/" & toFindThis & " \\([0-9]\\)/" & replaceWithThis & " \\1/'g"
    set theString to do shell script scriptText
end repeat
return theString

1 个答案:

答案 0 :(得分:0)

好的,使用sed -f命令文件技术,我得到了它的工作。该脚本采用制表符分隔的字符串或文件,然后从该文件构建一个sed命令文件。

property theString: "foo 1.0 is better than foo 2.0. The fee 5 is the best."
property substitutionList : "foo    bar
fee bee
fo  bo
bum bum" -- this tab delim list will have 78 terms

set tabReplace to "\\( [0-9]\\)/"
set paragraphReplace to "\\1/g
s/"

-- parse the replace string into lists
set commandString to ""
set otid to AppleScript's text item delimiters
set AppleScript's text item delimiters to tab
set commandString to text items of substitutionList
set AppleScript's text item delimiters to tabReplace
set commandString to "s/" & commandString as string
set AppleScript's text item delimiters to return
set commandString to text items of commandString
set AppleScript's text item delimiters to paragraphReplace
set commandString to (commandString as string) & "\\1/g"
set AppleScript's text item delimiters to otid

set commandFilePath to ((path to temporary items from user domain) as text) & "commandFile.sed"
try
    set fileRef to open for access file commandFilePath with write permission
    set eof of fileRef to 0
    write commandString to fileRef
    close access fileRef
on error
    close access fileRef
end try
set posixPath to POSIX path of file commandFilePath

set scriptText to "echo " & quoted form of theString & " | sed -f " & quoted form of posixPath
set theString to do shell script scriptText
return theString