2017-04-02 7 views
0

내 스크립트에서 theString은 일반적으로 200 단어 미만입니다. theFindList와 replaceWithList는 각각 78 개의 용어를 가지고 있습니다. 첫 번째 목록에서 각 용어를 찾을 때마다 찾아서 두 번째 목록에서 해당 용어로 바꿉니다. 스크립트는 정상적으로 실행되지만 반복 루프에서 78 가지 do shell 스크립트 호출에서 sed 명령을 수행하는 속도가 느립니다. 반복 수행을 위해 모든 것이 쉘로 전달되는 것이 빠를 것입니다. 어떻게해야합니까? 이제는 applescript에있는 반복되는 부분이 있습니다. Automator에 그 일을 맡길 것이므로 "쉘 스크립트 실행"액션에서 할 수있는 일이 효과가 있습니다. 탭으로 구분 된 문자열로 목록을 찾아 교체 할 수 있습니다. 찾기 및 바꾸기 목록은 상수이므로 셸 스크립트에 구운 목록이 필요하며 이전 작업에서 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

검색을 굽고 문자열을 셸 스크립트로 바꾸어도 괜찮 으면 하나의 sed 스크립트에서 수행 할 수 있습니까? 그렇게되면 루프와 시작 및 종료 실행 컨텍스트가 제거됩니다. 괜찮 으면's/foo/bar/g; s/fee/bee/g의 여러 행을 "fumbum.sed"에 쓰십시오. 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

좋습니다. 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