2017-04-02 5 views
0

私のスクリプトでは、theStringは通常200ワード未満です。 theFindListとreplaceWithListにはそれぞれの用語が78語あります。最初のリストから各用語のすべての出現を見つけ、それを2番目のリストの対応する用語で置き換えます。 スクリプトは正常に動作しますが、リピートループで78種類のdoシェルスクリプト呼び出しでsedコマンドを実行するのが遅いです。 反復がそこで実行されるためにすべてがシェルに渡された方が速くなります。それ、どうやったら出来るの? ここに、applescriptに含まれるものの関連するリピート部分があります。私はその事をAutomatorに入れているので、 "シェルスクリプトの実行"アクションで何かできることが働くでしょう。私は、タブで区切られたデータの文字列のリストを検索して置き換えることができます。 findとreplaceのリストは定数なので、シェルスクリプトに焼き付けられたものを必要とし、以前のアクションから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

検索をベイクして文字列をシェルスクリプトに置き換えても問題ない場合は、1つのsedスクリプトで実行することもできますか?それは、ループと多くの開始と終了の実行コンテキストを取り除くでしょう。 OKならば、 '' fumbum.sed ''s/foo/bar/g; s/fee/bee/gのいくつかの行に書きます。 s/fo/bo/g ... 'を呼び出し、' sed -f fumbum.sed'を呼び出します。 – Yunnosch

+1

's/foo \([0-9])/ bar \ 1/g'のような行のコマンドファイルを作成し、 'sed -f commandfile'を使用できますか? –

+0

@WalterA良い点、私は '\\([0-9] \\)'を忘れました。 – Yunnosch

答えて

0

[OK]を使用して、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