2

Finder has columns you can sort files by: Name, Size, Kind, Date, Comment, etc. These are shown as headers when Finder is in "List" mode, with respective file properties shown below.

  • If I Cmd+I a file, and change Comments to FOO, mdls shows FOO and Finder shows FOO.
  • If I set Comments to BAR from Terminal, mdls shows "BAR", but Finder still shows "FOO"!

How can I change the "Comment" field from Terminal so the change propagates to Finder?

$ xattr -w com.apple.metadata:kMDItemFinderComment "BAR" test.txt
$ mdls test.txt
kMDItemFinderComment = "BAR"

Update: I noticed that when using Finder / AppleScript, Comment is set to a Binary Property List containing the value. So maybe it's possible to circumvent AppleScript and increase performance?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<string>My comment</string>
</plist>

I tried editing the property list and feeding it back to xattr. However, xattr gives the error message Odd-length string even if the file size of hex is in fact an even number. Anyone?

xattr -p com.apple.metadata:kMDItemFinderComment a | xxd -r -p | plutil -convert xml1 -o plist -
nano plist
cat plist | plutil -convert binary1 -o - - | xxd -p -c 999 -u > hex
xattr -w -x com.apple.metadata:kMDItemFinderComment hex test.txt
1

mdls uses it's database to display file info, not extended attributes that are set on that file. So in order to make it work, you have to import the file to its database after changing the xattr with:

mdimport /path/to/file

In order to see the update comment in Finder, you can use AppleScript. Here's the code:

#!/bin/bash                                                                                                                                                                                                     

filepath="$1"
comment="$2"

/usr/bin/osascript -e "set filepath to POSIX file \"$filepath\"" \
-e "set theFile to filepath as alias" \
-e "tell application \"Finder\" to set the comment of theFile to \"$comment\""

Better version of that script can be found on StackOverflow by user l'L'l.

  • This works, but it's kind of slow. Changing the comments takes almost three seconds for a dozen files. Can the AppleScript be shortened or optimised? Is there a faster and shorter solution that does not involve AppleScript? I'll leave the question open for further suggestions. – forthrin Mar 23 '18 at 13:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .