I’m quite a newbie on applescript… I’m working on like a search in file thing… can you guys help me how I can search within the text file and flag it in a dialog box? here it goes… in a text file I should search the word “/S/D” so I have to open a file in TextEdit and begin searching the number of “/S/D” and search the number of “/angle” in the text file… then flag the number of “/S/D” and “/angle” in flag a dialog box “number of /S/D is ___ and number of /angle is ___”
I have pasted a script that will open the text file…
set response to (choose file) as string
tell application "TextEdit"
activate
open alias response
end tell
-- The variable of type "list" that contains every text to search
-- You can change this variable with another texts if you want
set theTextToSearchList to {"/S/D", "/angle"}
-- The variable with the path of text file that contains all text to analyse
set theTextFilePath to (choose file without invisibles) as string
-- The variable to contains all text to analyse from text file
set theTextToAnalyse to read file theTextFilePath as string
-- Initialise a variable which will receive the result of the number
-- of various texts to search existing in the text to analyze
set theResultList to {}
-- A loop to search each text in the text to analyse
repeat with theTextToSearch in theTextToSearchList
-- A first test to make sure that the text to search
-- exist well in the text to analyze before its calculation
if theTextToSearch is in theTextToAnalyse then
-- It is one of the method possible, while handling
-- the "text item delimiters" property of AppleScript
set text item delimiters of AppleScript to theTextToSearch
-- Temporary variable which contains a list of text items
set theTextItemsList to text items of theTextToAnalyse
-- Give the default value of the "text item delimiters" property
set text item delimiters of AppleScript to ""
-- Count the existing number of items in the temporaray variable (less 1),
set theResultCount to (count theTextItemsList) - 1
-- The result text variable with a "return" character at end
set theResultText to "Number of \"" & theTextToSearch & "\" = " & theResultCount & return
-- Put the result text in the result variable list
set end of theResultList to theResultText
end if
end repeat
-- Display dialog the result
display dialog (theResultList as string) with icon 1
This sort of thing is usually best done with the shell. That way, you don’t have to open a GUI app and script/error-handle it.
Quick example:
So if you wanted to do it in AppleScript, you’d do this:
set theFile to POSIX path of (choose file)
set x to (do shell script "/usr/bin/grep -o '/S/D'" & space & theFile & space & "| /usr/bin/wc -l")
set y to (do shell script "/usr/bin/grep -o '/angle'" & space & theFile & space & "| /usr/bin/wc -l")
display dialog "Number of /S/D is:" & space & x & return & return & "Number of /angle is:" & space & y
(I cleaned up the dialog a little bit to make it more readable.)