2011-06-30 39 views
1

此代碼顯然不會工作,但我正在尋找語法更改以使其工作。Applescript-對於grep發現的每個項目

for every item that grep finds 
    set myCommand to do shell script "grep -w word test.log" 
    set mySecondCommand to do shell script "grep -w end test.log" 
end 

下面的輸出應該是正確的(我想):

word 
end 
word 
end 

,而不是我得到的,因爲我沒有這個理論「爲每一個項目是grep的發現」的聲明(我不知道想要這個輸出):

word 
word 
end 
end 

回答

1

你的初始grep結果將是字符串格式,例如。一個長串。爲了迭代它們,您需要將字符串轉換爲列表,因此我使用「段落」命令。一旦你有了列表格式的初始grep結果,那麼你可以使用重複循環來處理列表中的項目。在處理這些項目時,您需要將這些結果存儲在新列表中,以便在腳本結尾處可以查看結果。像這樣...

set firstWord to "word" 
set secondWord to "end" 

-- use the ls command and grep to find all the txt documents in your documents folder 
set aFolder to (path to documents folder) as text 
set grepResults to do shell script "ls " & quoted form of POSIX path of aFolder & " | grep \"txt\"" 
set grepResultsList to paragraphs of grepResults 

-- search the found txt documents for the words 
set totalResults to {} 
repeat with aResult in grepResultsList 
    set thisPath to aFolder & aResult 
    try 
     set myCommand to paragraphs of (do shell script "grep -w " & firstWord & space & quoted form of POSIX path of thisPath) 
     set myCommandCount to count of myCommand 
     set end of totalResults to {thisPath, firstWord, myCommandCount, myCommand} 
    end try 

    try 
     set mySecondCommand to paragraphs of (do shell script "grep -w " & secondWord & space & quoted form of POSIX path of thisPath) 
     set mySecondCommandCount to count of mySecondCommand 
     set end of totalResults to {thisPath, secondWord, mySecondCommandCount, mySecondCommand} 
    end try 
end repeat 
return totalResults 
+0

非常感謝! – evdude100

+0

沒問題,很樂意幫忙。祝你好運。 – regulus6633