Applescript - для каждого элемента, который находит grep - PullRequest
1 голос
/ 30 июня 2011

Этот код, очевидно, не будет работать, но я ищу изменение синтаксиса, чтобы заставить его работать.

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 Ответ

1 голос
/ 30 июня 2011

Ваши начальные результаты 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
...