1

此代码显然不起作用,但我正在寻找语法更改以使其工作。

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
4

1 回答 1

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
于 2011-06-30T14:36:23.360 回答