I had some old (we’re talking Apple IIGS era old) files that I wanted to keep around, and I wanted Spotlight to show them if there was a valid hit. Many of the file formats I cannot read anymore, but even a raw dump of the file could at least reveal the information I needed. What I could not find online was a way to write Spotlight-findable data from the command line. My idea was to run the strings command and embed that as a comment. I finally figured it out on my own, and it involves embedding AppleScript in a shell script via osascript.

Without further ado, here is the bash function that I keep in my .bash_profile file (along with this handy function for assigning Finder labels).

[bash]# Assign a finder comment to a file
if [ $# -lt 2 ]; then
echo “USAGE: findercomment file comment [words can continue]”
echo “Sets the Finder comment for a file.”
echo “Example: findercomment stevejobs.jpg this one will be worth money some day”
osascript – “$@” << EOF
on run argv
set text item delimiters of AppleScript to " "
set theComment to (items 2 through end of argv) as string
set theFile to POSIX file (item 1 of argv) as alias
tell application "Finder"
set comment of theFile to theComment
end tell
end run

With that function defined, I was able to recurse through a directory, run strings to extract words, and assign the words as a Finder comment to the files.

[bash]find . | while read F; do
echo “$F”
COMMENTS=$(strings “$F”)
findercomment “$F” “$COMMENTS”

There’s probably an extra step I could take to filter the output of strings against a dictionary, but I left it as is. Enjoy.