I got started on this last night and decided to finish it today even though you have a good solution from @Nige_S. I wanted to learn how to create and use dictionaries in Keyboard Maestro, a feature I've never used before.
File Prefix Count.kmmacros (4.9 KB)
Image of macro
This macro uses a dummy list of files:
1z_thing
2z thing
3z_thing1
3z thing2
3z_thing3
6z thing1
6z_thing2
12z thing
The real list of files could come from an ls
command as @Nige_S suggests.
The Perl script is this:
#!/usr/bin/perl
# Make a hash of the prefix counts
while (<>) {
@file_parts = split /z/;
$count{$file_parts[0]}++;
}
# Use the hash to make an array of JSON parts
while( ($k, $v) = each %count ){
push @json_parts, qq("$k": $v);
}
# Assemble the parts into a complete JSON string
print "{" . join(", ", @json_parts) . "}";
Perl has a well-known way of creating a dictionary (called a hash in Perl) of occurrence counts. I used that in the first few lines, with the keys of the hash being the prefix before the “z.” The rest of the code prints the hash out in JSON format. The output of the script is
{"12": 1, "3": 3, "2": 1, "6": 2, "1": 1}
As you can see, Perl hashes aren't sorted by key, but that's OK.
This script could just as easily been written in Python, but since Apple has stopped installing Python by default, I decided to go with Perl.
The Set Dictionary action uses the JSON output of the Perl script to create a Keyboard Maestro dictionary, which you can then use to get counts of any of the prefixes using tokens like
%Dictionary[LocalFilePrefixCount, 6]%
which would return 2 because there are two files with a prefix of “6z.”
In the last few steps, I loop through the dictionary keys collection to print out all the dictionary keys and their values.