Hello all,
I’ve been struggling with this: one of the options in my app has to allow the user to count all the occurrences of a user-defined string within all the files of a folder.
It has to open each file one by one, and add the number of occurrences found to the count, and return the total number at the end.
I came up with something a while ago with the help of a friend, but it only processes 1 file at a time and I’m having a hard time adapting the code so that it does what I mentionned above. Here’s the code:
on run
set myFile to choose file with prompt "Choose a file: "
set theText to readFile(myFile)
set theChar to text returned of (display dialog "What are you trying to count ?" default answer "a")
set occNbr to findLr(theText, theChar)
display dialog "Number of Occurences : " & occNbr
end run
on readFile(PathFile) -- we read the file
try
set foo to (open for access PathFile)
set theData to (read foo)
close access foo
on error
close access foo
end try
return theData
end readFile
on findLr(the_string, charTF)
set AppleScript's text item delimiters to charTF --use of the searched string to separate bits
set the_list to text items of the_string --put those bits in a list
set charNbr to ((count of the_list) - 1) --count those bits, minus 1
set AppleScript's text item delimiters to ""
return charNbr
end findLr
So here I tried doing something like this :
-- ... my stuff
if state of button "countOccurrences" of drawer "drawer" of window "main" is 1 then
set the item_list to list folder theFolder without invisibles
set theFolder to theFolder as string
repeat with i from 1 to (count of the item_list)
set this_item to item i of the item_list
set this_item to ((theFolder) & this_item as string) as alias
set this_info to info for this_item
set listChar to {}
set theText to readFile(this_item)
set theChar to contents of text field 1 of box 2 of tab view item 1 of tab view 1 of window 1
set occNbr to findLr(theText, theChar)
end repeat
set contents of text field "occurrences" of drawer "drawer" of window "main" to occNbr
end if
on readFile(PathFile) -- we read the file
try
set foo to (open for access PathFile)
set theData to (read foo)
close access foo
on error
close access foo
end try
return theData
end readFile
on findLr(the_string, charTF)
set AppleScript's text item delimiters to charTF --use of the searched string to separate bits
set the_list to text items of the_string --put those bits in a list
set charNbr to ((count of the_list) - 1) --count those bits, minus 1
set AppleScript's text item delimiters to ""
return charNbr
end findLr
but it says “the file wasn’t open” … what do you think I’m doing wrong ?
I know I don’t have anything to add the number of occurrences to the total count yet, but I need to fix the problem of files not opening first …
Thanks in advance for any help