Search code examples
csshtmlcountapplescriptbbedit

How to get the count of a class with AppleScript?


Learning AppleScript I'm trying to practice and I wanted to see if I could get the count of a class in an .xhtml file.

In my BBEdit project I set a variable for the project with:

set this_project to file of project document 1

made sure to target all the .xhtml files with:

set total_xhtml to {search mode:grep, case sensitive:false, match words:false, extend selection:false, returning results:true, filter:{ID:"111232452", filter_mode:and_mode, filter_terms:{{operand:"xhtml", field:«constant ****FnSf», operator:op_is_equal}}}}

but when I try to count the class for each file I'm stumped..

I did try:

set varCount to count class=\"foobar\"" of (this_project in total_xhtml)

If I try set varCount to count class=\"foobar\"" it returns a number in the AppleScript Editor but how can I get the full count for each file in a project?


Solution

  • Just realized I never accepted an answer to my question and I wanted to close out this Q&A. I didn't choose the provided answer because text item delimiters were firing an incorrect count from the file and I wanted an approach that didn't call on a do shell.

    In AppleScript and BBEdit if you reference the Dictionary there is FIND:

    enter image description here

    and with a repeat loop I was able to step through each occurrence of class="foobar":

    ## beginning of file
    select insertion point before first character of text document text document 1 
    
    set countClass to 0
    
    repeat
        ## find pattern
        set findClass to find "class=\"foobar\"" searching in text 1 of text document text document 1 options {options} with selecting match 
    
        ## exit after no more patterns
        if not found of findClass then exit repeat 
    
        ## increment for every occurrence
        set countClass to countClass + 1 
    end repeat
    
    ## return total count of pattern
    return countClass 
    

    With the above repeat I was able to step through each file and total up every occurrence of class foobar. Hope this helps the next person.