I would like to me able to set (and get) a custom metadata attribute for any file.
What is the best way to do this?
Thanks
The OpenMeta framework is a de-facto third-party standard for adding metadata to OS X files using extended attributes. It is used by a number of third-party applications.
Custom attribute names work for me:
$ xattr -w com.apple.metadata:MyAttribute gfdylvyieo a.txt
$ mdls -n MyAttribute a.txt
MyAttribute = "gfdylvyieo"
$ mdfind gfdylvyieo
/private/tmp/a.txt
$ mdfind 'MyAttribute=*'
/private/tmp/a.txt
xattr -wx
is not needed if the value is plain text:
xattr -w com.apple.metadata:kMDItemFinderComment aa file.txt
When you add a Spotlight comment from Finder, it is stored both as an extended attribute and in a .DS_Store file. If you just add an extended attribute, the Spotlight comment field appears blank in Finder, but the comment metadata is still indexed by Spotlight.
This sounds like a job for extended attributes. You can get and set them from the command line with xattr, and from programs with getxattr and setxattr.
However, extended attributes are (at least generally) not indexed by Spotlight. The only exception I know of to this is the "com.apple.metadata:kMDItemFinderComment" attribute, which should contain a binary-format plist with the actual indexable comment (see @PurplePilot's answer). This page claims spotlight will index other xattrs prefixed by "com.apple.metadata:", but I haven't gotten it to work.
If you want to programmatically set the "Finder Comment" of a file (see @PurplePilot's answer), try this:
1) Create a regular xml plist file with your comments:
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<string>My Custom Comment</string>
</plist>
2) Convert the plist to the accepted binary format:
plutil -convert binary1 my_custom_comment.plist
3) Using xattr
, set the kMDItemFinderComment metadata:
xattr -wx "com.apple.metadata:kMDItemFinderComment" "`xxd -ps my_custom_comment.plist`" MyFile
You can see with xattr -l MyFile
that the comments are there and in the right binary format, but for some reason Finder doesn't show it (at least for me) in the Comments column.
Searching against the spotlight database with mdfind "My Custom Comment"
will return all the files with this comment.
Right click and Info, or cmd + i when the file is selected in the finder will open an information panel and you can add data at the top that will be referenced in Spotlight. Is called Spotlight Comments. You can do this with directories as well. I am not sure if it is the best way but it is the only way i know of doing it.
来源:https://stackoverflow.com/questions/8530825/mac-os-x-add-a-custom-meta-data-field-to-any-file