Append string to all text files in a folder

Basic question but I can't figure it out -- I need to append a short string of text to all the markdown files in a particular folder. I found this script but I don't know how to use it with Keyboard Maestro:

for file in *.md; do
  echo 'MyString' >> "$file"
done

How do I wrap this in a KM macro for future use, and how would I execute it? I don't really care how it's triggered, I can customize that later. But how would I tell the system to run this script on a particular folder? Or is there a better way?

You would use Keyboard Maestro's "Execute Shell Script" action.

If the folder is always the same, you could specify it in the shell script:

chdir "$HOME/Documents/My Folder/"

for file in *.md; do
  echo 'MyString' >> "$file"
done

chdir stands for Change Directory (you can also abbreviate it as simply cd

BTW / FWIW I would recommend adding a blank line or two before your 'MyString' but that's just personal preference. When using echo you can add a blank line by adding \n (n as in newline)

This would add two blank lines to the end of the file and then MyString:

chdir "$HOME/Documents/My Folder/"

for file in *.md; do
  echo '\n\nMyString' >> "$file"
done

Again, that's just personal preference and you may have reasons not to want that, but I thought I'd mention it.

If you want to be able to select a folder in Finder and tell Keyboard Maestro to append to all the files in the selected folder…

…then you would want to refer to the Finder's Selection page from the Keyboard Maestro Wiki:

https://wiki.keyboardmaestro.com/collection/Finders_Selection

Feel free to ask more questions if you need more help. Happy to share what shell script + Keyboard Maestro knowledge I have to offer.

As mentioned by @tjluoma, this is easily done using the KM For Each action with either a Folder Contents collection or a Finders Selection collection.

KM even has a Append Text to a File action.

That will make it easier to maintain and expand on, without having to have a detailed knowledge of shell scripting. It is also safer.

There are several good Macro examples in the Forum's Best Macro List , as well as in the forum in general. Do a forum search on "files".

Please let us know if you have any further questions.

1 Like

Gotcha, the part I was missing was the Finder Selection part. Thanks very much, and for the tip on the new line regex. The fact that you can put \n within a single quote throws me off. I'm used to double quotes, and they usually mean "take everything here literally."

I like your interviews on the MPU podcast, by the way!

Both very helpful, thank you @JMichaelTX

The Best Macro List has been a favorite for a while, thanks. I honestly try to search the forums for answers before I post, but often I can't find them until someone provides a link. Cheers.