How can I add OS X “tags” to files programmatically?

前端 未结 9 1488
轻奢々
轻奢々 2021-01-29 22:23

Since Mavericks, OS X has had the ability to tag & colour files in Finder.

\"finder

Is there any

9条回答
  •  面向向阳花
    2021-01-29 22:38

    I add this answer, because OP asked for a shell script and tagged it bash. I wrote this Automator service, which tags the selected file with the tags of another file. I have added comments to outline the use of bash's interaction with the tags and colours using bash script.

     

    Basics

    In scripts both OpenMeta and Mavericks tags can be accessed with the command xattr. Using it without modifiers, $ xattr [file], gives a list of set attributes. $ xattr -h gives a nice guide to usage.

    Mavericks' tags are in com.apple.metadata:_kMDItemUserTags, while OpenMeta tags can be in a variety of attributes. Amongst others com.apple.metadata:kOMUserTags, org.openmetainfo:kMDItemOMUserTags and org.openmetainfo:kOMUserTags.

    Mavericks handles colours and tags in different attributes, by placing tags in _kMDItemUserTags and colours in FinderInfo for every file. This is a bizarre choice, and it is one of the reasons Finder struggles under the pressure of tagging. If you have 800 files tagged kapow, each in a different folder, and you subsequently choose the colour blue for kapow, Finder has to find and alter attributes for every single file.

    You can play around with the oddity by removing the com.apple.FinderInfo attribute from a tagged and coloured file: $ xattr -d com.apple.FinderInfo [file]. The colour will disappear in Finder listings, but the tag (and its colour) remains associated with the file.

     

    Bash script to import tags from another file

    In the script, the selected file(s) in Finder is/are saved to the variable $tagless, and the chosen supplier of tags is $tagfull.

    TAGFULID=${#@}
    TAGFUL=${!TAGFULID}
    
    ## Use xattr to read all existing tags:
    ATTRS=$(xattr "$TAGFUL")
    
    for f in "$@" ## For every selected file in Finder, do:
    do
        if("$TAGFUL"="$f") ## Is the supplier of tags is amongst the selected files?
        then
            break
        fi
    
        if [[ "$ATTRS" == *kMDItemUserTags* ]] ## Are there tags?
            then
            ## Load tags:
            TAGS=$(xattr -px com.apple.metadata:_kMDItemUserTags "$TAGFUL")
            ## Write tags:
            xattr -wx com.apple.metadata:_kMDItemUserTags "$TAGS" "$f"
        fi
        if [[ "$ATTRS" == *FinderInfo* ]] ## Are there colours?
        then
            ## Load colour:
            FINDERINFO=$(xattr -px com.apple.FinderInfo "$TAGFUL")
            ## Write colour:
            xattr -wx com.apple.FinderInfo "$FINDERINFO" "$f"
        fi
    done
    

    The Automator service

提交回复
热议问题