Counting Text Strings In a Directory

165 views
Skip to first unread message

Richard Fairbanks

unread,
Dec 7, 2021, 9:44:14 PM12/7/21
to BBEdit Talk
Greetings, folks!

I want BBEdit to return the number of times a text string appears in the files in a directory. The following works to replace any such text:

tell application "BBEdit" to replace "text1" using "text2" searching in {file "path:to:directory:"}

But I can’t figure out how to get the number of text strings found. The following always returns a count of “1” (there are hundreds):

tell application "BBEdit" to return count (find "text1" searching in {file "path:to:directory:"} options {showing results:false}) -- the script errors out without the “options {showing results:false}”; it also errors out with “options {showing results:true}”.

Thoughts?

Blessings, and thank you!

Christopher Stone

unread,
Dec 7, 2021, 11:20:41 PM12/7/21
to BBEdit-Talk
On Dec 07, 2021, at 20:44, Richard Fairbanks <li...@F-P-I.com> wrote:
I want BBEdit to return the number of times a text string appears in the files in a directory. The following works to replace any such text:


Hey Richard,

The simple way is to do a straight file search:


If you want to script it then you need to do something like this:

--------------------------------------------------------
# Auth: Christopher Stone
# dCre: 2021/12/07 22:17
# dMod: 2021/12/07 22:17 
# Appl: BBEdit
# Task: Count the Number of Files Containing a Search String – Recursive-File-Search
# Libs: None
# Osax: None
# Tags: @Applescript, @Script, @ASObjC, @BBEdit, @Count, @Files, @Containing, @Search, @String, @Recursive, @Search
--------------------------------------------------------
use AppleScript version "2.4" --» Yosemite or later
use framework "Foundation"
use scripting additions
--------------------------------------------------------

set searchDir to "~/test_directory/Many_Files_6000/"

set searchDir to ((current application's NSString's stringWithString:searchDir)'s ¬
    stringByExpandingTildeInPath) as text

tell application "BBEdit"
    set foundRecord to find "three\\nfour" searching in searchDir options {search mode:grep, case sensitive:false, starting at top:true, returning results:true}

    

    if found of foundRecord then
        return length of found matches of foundRecord
    end if

    

end tell

--------------------------------------------------------


--
Best Regards,
Chris

Richard Fairbanks

unread,
Dec 9, 2021, 7:26:19 PM12/9/21
to BBEdit Talk
Hi, Chris!

Thank you so much for the script; I have been testing it out with various configurations, and it’s working great!

You have shown me that after many years, I still have a lot to learn about the endless enigma known as “AppleScript.”

;-)

Blessings, and thank you!
Reply all
Reply to author
Forward
0 new messages