Is it complicated to write an AppleScript to count the number of lines starting with #?

I would like to count the number of header lines in a mardown text, ie basically count the number of lines starting with # (hashtag) (ie ⌃# in regex terms) in the clipboard (I will start by copying the text to the clipboard)
thanks in advance for your time and help

I’m not sure about AppleScript, but it’s fairly easy to do with a shell script (and you can call a shell script from AppleScript, so maybe that will suffice?)


pbpaste | egrep -c '^#' 

pbpaste says “show me all of the text on the pasteboard/clipboard”

| says “filter the information on the left through the program on the right”

egrep will search for text using regular expressions

-c tells egrep to return a count of the lines which match.

^# is what you are searching for, which you seem to already know from other regex experience.

4 Likes

a great solution.
I can implement with keyboard maestro
thanks very much !

FWIW, if, for any reason you did want to do this in a monolingual osascript context (rather than polyglotally farming some part of it out to a combination of shell semantics + a kleene algebra :slight_smile:

then one approach would be to define (in JS) what happens to the total count at the margin:

// talliedHeading :: (Int, String) -> Int
const talliedHeading = (total, s) =>
    s.startsWith('#') ? (
        1 + total
    ) : total;

and plug that into .reduce – the JS version of the more general [fold pattern](http://www.cs.nott.ac.uk/~pszgmh/fold.pdf).

So broadly, something like this:

(() => {
    'use strict';

    // main :: IO ()
    const main = () =>
        readFile('~/Desktop/withHeadings.md')
        .split(/[\r\n]+/)
        .reduce(talliedHeading, 0);


    // talliedHeading :: (Int, String) -> Int
    const talliedHeading = (total, s) =>
        s.startsWith('#') ? (
            1 + total
        ) : total;


    // --------------------- GENERIC ---------------------

    // readFile :: FilePath -> IO String
    const readFile = fp => {
        // The contents of a text file at the
        // path file fp.
        const
            e = $(),
            ns = $.NSString
            .stringWithContentsOfFileEncodingError(
                $(fp).stringByStandardizingPath,
                $.NSUTF8StringEncoding,
                e
            );
        return ObjC.unwrap(
            ns.isNil() ? (
                e.localizedDescription
            ) : ns
        );
    };

    // MAIN ---
    return main();
})();
2 Likes

Right; I wondered why AppleScript.

And I make the linkage to a similarish-sounding post elsewhere.