@mrpasini Love it! But...
When using grep
, \n
isn't so much a new line character as it is a string delimiter. You can use sed
(and sometimes tr
) to put those delimiters anywhere you like, including in front of whatever item you are interested in isolating and counting.
Say, for example, you want to count the number of instances of the letter 'a' in the clipboard. The following does the trick.
pbpaste | sed "s/a/\n&/g" | grep "a" | wc -l
Of course 'a' could be whatever you want it to be, including the contents of a shell variable, which can be the value of a KM variable.
pbpaste | sed "s/$KMVAR_varName/\n&/g" | grep "$KMVAR_varName" | wc -l
(You do have to worry about special characters and the like, but that is always the case.)
A somewhat more interesting case. Suppose that you want to know not only how many actions there are in a macro, but wanted a complete list of XML key types present along with the number of each.
pbpaste | sed "s/<key>/\n&/g" | grep "<key>" | awk -F'<key>|</key>' '{print $2}' | sort | uniq -c
sed "s/<key>/\n&/g"
puts every instance of "<key>
" at the start of its own line.
grep "<key>"
finds those lines.
awk
uses regular expressions as field separators, so awk -F'<key>|</key>' '{print $2}'
prints the text between <key>
and </key>
.
sort
alphabetizes the result and passes it on to uniq -c
, which prints out each unique word along with the number of times it was found. Among those results will be something like "95 ActionUID", which is the number of actions.
The suite of UNIX command line tools grew up kind of organically over the course of the last 50 years or so as people had to tackle exactly these sorts of problems, among others. A long time ago I stopped asking "can you do such and such?" because the answer almost always turned out to be, "yes."
A statement, I have been delighted to discover, that is also true of Keyboard Maestro.