• macOS - mdls, mdfind, mdutil, xargs 命令使用



    使用示例

    
    # 查看文件元数据
    $ mdls /Users/xx/Desktop/a.txt 
    _kMDItemDisplayNameWithExtensions      = "a.txt"
    kMDItemContentCreationDate             = 2022-06-22 01:19:49 +0000
    kMDItemContentCreationDate_Ranking     = 2022-06-22 00:00:00 +0000
    kMDItemContentModificationDate         = 2022-06-22 01:19:53 +0000
    kMDItemContentModificationDate_Ranking = 2022-06-22 00:00:00 +0000
    kMDItemContentType                     = "public.plain-text"
    kMDItemContentTypeTree                 = (
        "public.plain-text",
        "public.text",
        "public.data",
        "public.item",
        "public.content"
    )
    kMDItemDateAdded                       = 2022-06-22 01:19:49 +0000
    kMDItemDateAdded_Ranking               = 2022-06-22 00:00:00 +0000
    kMDItemDisplayName                     = "a.txt"
    kMDItemDocumentIdentifier              = 0
    kMDItemFSContentChangeDate             = 2022-06-22 01:19:53 +0000
    kMDItemFSCreationDate                  = 2022-06-22 01:19:49 +0000
    kMDItemFSCreatorCode                   = ""
    kMDItemFSFinderFlags                   = 0
    kMDItemFSHasCustomIcon                 = (null)
    kMDItemFSInvisible                     = 0
    kMDItemFSIsExtensionHidden             = 0
    kMDItemFSIsStationery                  = (null)
    kMDItemFSLabel                         = 0
    kMDItemFSName                          = "a.txt"
    kMDItemFSNodeCount                     = (null)
    kMDItemFSOwnerGroupID                  = 20
    kMDItemFSOwnerUserID                   = 501
    kMDItemFSSize                          = 9
    kMDItemFSTypeCode                      = ""
    kMDItemInterestingDate_Ranking         = 2022-06-22 00:00:00 +0000
    kMDItemKind                            = "纯文本文稿"
    kMDItemLogicalSize                     = 9
    kMDItemPhysicalSize                    = 4096
    
    
    # 查看某个属性
    $ mdls -name kMDItemDisplayName /Users/xx/Desktop/a.txt 
    kMDItemDisplayName = "a.txt"
    
    
    # 只查看属性对应的值
    $ mdls -raw  -name kMDItemDisplayName /Users/xx/Desktop/a.txt 
    a.txt
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    # 查找所有属性中包含 image 的所有文件
    $ mdfind image
    
    # 查找文件名为 a.txt 的文件
    $ mdfind "kMDItemDisplayName='a.txt'"
    /Users/xx/Desktop/a.txt
    /Users/xx/Documents/code/spider/code/trans/bleu/a.txt
    
    
    # 模糊查找文件名为 a*.txt 的文件
    $ mdfind "kMDItemDisplayName='a*.txt'"
    /usr/share/vim/vim82/doc/arabic.txt
    /usr/share/vim/vim82/doc/autocmd.txt
    /System/Library/Perl/5.18/Unicode/Collate/allkeys.txt
    ..
    
    
    # 持续搜索
    $ mdfind -live "kMDItemDisplayName='a.txt'" 
    /Users/xx/Desktop/a.txt
    /Users/xx/Documents/code/spider/code/trans/bleu/a.txt
    [Type ctrl-C to exit]
    Query update: 3 matches  # 在文件夹A创建 a.txt 后
    Query update: 4 matches  # 在文件夹B创建 a.txt 后
    ^C
    
    # 持续搜索,文件变化后再次打印
    $ mdfind -live -reprint "kMDItemDisplayName='a.txt'" 
    
    # 符合条件的数量
    $ mdfind -count  "kMDItemDisplayName='a.txt'" 
    4
    
    # 只在指定目录查询
    $ mdfind -onlyin /Users/xx/Desktop/ "kMDItemDisplayName='a.txt'" 
    /Users/xx/Desktop/a.txt
    
    # 根据名字查询
    $ mdfind -name a.txt
    /Users/xx/Desktop/a.txt
    /Users/xx/Documents/a.txt
    /Users/xx/Documents/software/a.txt
    /Users/xx/Documents/code/spider/code/trans/bleu/a.txt
    
    
    $ mdfind -literal  "kMDItemDisplayName='a.txt'" 
    /Users/xx/Documents/software/a.txt
    /Users/xx/Documents/a.txt
    /Users/xx/Desktop/a.txt
    /Users/xx/Documents/code/spider/code/trans/bleu/a.txt
    
    # 限制搜索类型 kind 可参考元信息 kMDItemKind,设置为 text, audio, movie 
    $ mdfind kind:image -name mac
    /System/Library/Displays/Contents/Resources/Overrides/Models/Mac-7BA5B2D9E42DDD94.tiff
    /System/Library/PrivateFrameworks/CoreBluetoothUI.framework/Versions/A/Resources/Mac_Settings_NC-Selected-B443.png
    /System/Library/PrivateFrameworks/CoreBluetoothUI.framework/Versions/A/Resources/Mac_Settings_NC-Unselected-B443.png 
    ...
    
    # 查找所有文本文件
    $ mdfind kind:text  
    
    # 查找尺寸范围内的文件 
    $ mdfind 'kMDItemFSSize >= 5000 && kMDItemFSSize <= 5005)'
    
    # 查找修改时间在此后的文件
    $ mdfind 'kMDItemFSContentChangeDate >= $time.iso(2022-06-21T13:44Z)'
    
    # 创建时间在范围内的
    $ mdfind 'kMDItemFSCreationDate >= $time.now(-60)'
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71

    # 关闭索引
    $ sudo mdutil -i off / 
    Password:
    /:
    2022-06-22 10:25:20.505 mdutil[3506:63385] mdutil disabling Spotlight: / -> kMDConfigSearchLevelFSSearchOnly
    	Indexing disabled.
    
    
    # 查看状态
    $ mdutil -s /
    /:
    	Indexing disabled.
    
    
    # 开启索引(重建索引)
    $ sudo mdutil -i on / 
    /:
    	Indexing enabled. 
    
    
    $  mdutil -s /
    /:
    	Indexing enabled. 
        
    
    # 删除索引
    $ sudo mdutil -E / 
     
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    
    $ echo 'hello' | xargs echo
    hello
    
    
    # ,head 查看搜索结果
    $ mdfind kMDItemDisplayName='a.txt'  |  xargs head
    ==> /Users/xx/Documents/software/a.txt <==
    abc
    123
    
    
    ==> /Users/xx/Desktop/a.txt <==
    abc
    123
    
    
    ==> /Users/xx/Documents/code/spider/code/trans/bleu/a.txt <==
    a
    b
    ca
    
    
    # 传两个参数给后面的命令,此处只 head 两个文件
    $ mdfind kMDItemDisplayName='a.txt'  |  xargs -n 2  head
    
    
    # 一些用法
    # 找到所有jpg文件并压缩,那么可以如此操作:
    $ find dirname -name *.jpg -type f -print | xargs tar -cvzf images.tar.gz
    
    # 批量删除同名文件
    $ find dirname -name filename | xargs rm -rf
    
    # 批量修改文件名,此处 a.txt 变为 a.txt.mp4
    $ mdfind kMDItemDisplayName='a.txt'  |  xargs -n 1 -I {} mv {} {}.mp4
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    manual

    mdls

    NAME

    mdls – lists the metadata attributes for the specified file


    SYNOPSIS

    mdls [-name attributeName] [-raw [-nullMarker markerString]] file …

    DESCRIPTION
    The mdls command prints the values of all the metadata attributes associated with the files provided as an argument.

    The following options are available:

    • -name, Print only the matching metadata attribute value. Can be used multiple times.
    • -raw, Print raw attribute data in the order that was requested.
      Fields will be separated with a ASCII NUL character, suitable for piping to xargs(1) -0.
    • -nullMarker, Sets a marker string to be used when a requested attribute is null.
      Only used in -raw mode. Default is “(null)”.

    mdfind manual

    NAME

    mdfind – finds files matching a given query


    SYNOPSIS

    mdfind [-live] [-count] [-onlyin directory] [-name fileName | -s smartFolderName | query]


    DESCRIPTION

    The mdfind command consults the central metadata store and returns a list of files that match the given metadata query.
    The query can be a string or a query expression.

    The following options are available:

    • -0, Prints an ASCII NUL character after each result path.
      This is useful when used in conjunction with xargs -0.
    • -live, Causes the mdfind command to provide live-updates to the number of files matching the query.
      When an update causes the query results to change the number of matches is updated.
      The find can be cancelled by typing ctrl-C.
    • -count, Causes the mdfind command to output the total number of matches, instead of the path to the matching items.
    • -onlyin dir, Limit the scope of the search to the directory specified.
    • -name fileName, Searches for matching file names only.
    • -literal, Force the provided query string to be taken as a literal query string, without interpretation.
    • -interpret, Force the provided query string to be interpreted as if the user had typed the string into the Spotlight menu.
      For example, the string “search” would produce the following query string:

    (* = search* cdw || kMDItemTextContent = search* cdw)


    EXAMPLES
    The following examples are shown as given to the shell.

    This returns all files with any metadata attribute value matching the string “image”:

    $ mdfind image
    
    • 1

    This returns all files that contain “MyFavoriteAuthor” in the kMDItemAuthor metadata attribute:

    $ mdfind "kMDItemAuthors == '*MyFavoriteAuthor*'"
    
    • 1

    This returns all files with any metadata attribute value matching the string “skateboard”.
    The find continues to run after gathering the initial results, providing a count of the number of files that match the query.

    $ mdfind -live skateboard
    
    • 1

    To get a list of the available attributes for use in constructing queries, see mdimport(1), particularly the -X switch.


    Comparison Operators

    By default mdfind will AND together elements of the query string.

    • |, (OR) To return items that match either word, use the pipe character: stringA|stringB
    • -, (NOT) To exclude documents that match a string -string
    • =, “equal”
    • ==, “equal”
    • !=, “not equal”
    • < and >, “less” or “more than”
    • <= and >= “less than or equal” or “more than or equal”
    • InRange(attributeName,minValue,maxValue) Numeric values within the range of minValue to maxValue in the specified attribute.

    Value Comparison modifiers
    Modifier Description

    • c, The comparison is case insensitive.
    • d, The comparison is insensitive to diacritical marks.

    mdutil

    NAME

    mdutil – manage the metadata stores used by Spotlight


    SYNOPSIS

    mdutil [-pEsav] [-i on | off] mountPoint …


    DESCRIPTION
    The mdutil command is useful for managing the metadata stores for mounted volumes.

    The following options are available:

    • -i on | off, Sets the indexing status for the provided volumes to on or off.
      Note that indexing may be delayed due to low disk space or other conditions.
    • -d, Disables Spotlight searches on the provided volume.
    • -E, This flag will cause each local store for the volumes indicated to be erased.
      The stores will be rebuilt if appropriate.
    • -s, Display the indexing status of the listed volumes.
    • -a, Apply command to all stores on all volumes.
    • -t, Resolve files from file id with an optional volume path or device id.
    • -p, Spotlight caches indexes of some network devices locally. This option requests that a local caches be flushed to the appropriate network device.
    • -V volume-path, Apply command to all stores on the specified volume.
    • -v, Print verbose information when available.
    • -r plugins, Ask the server to reimport files for UTIs claimed by the listed plugin.
    • -L volume-path, List the directory contents of the Spotlight index on the specified volume.
    • -P volume-path, Dump the VolumeConfig.plist for the specified volume.
    • -X volume-path, Remove the Spotlight index directory on the specified volume.
      This does not disable indexing.
      Spotlight will reevaluate volume when it is unmounted and remounted, the machine is rebooted, or an explicit index command such as ‘mdutil -i’ or
      ‘mdutil -E’ run for the volume.

    mdimport


    NAME

    mdimport – import file hierarchies into the metadata datastore.


    SYNOPSIS

    mdimport [-itpAXLr] [-d level] [-o -outputfile] [ file | directory … ]


    DESCRIPTION

    mdimport is used to test Spotlight plug-ins, list the installed plug-ins and schema, and re-index files handled by a plug-in when a new plug-in is installed.
    The following options are available:

    • -i, Request Spotlight to import file or recursively import directory.
      The files will be imported using the normal mechanisms and attributes will be stored in the Spotlight index. This is the implied switch if none are specified.
    • -t, Request Spotlight to test import file, sending the result back to mdimport for possible further processing.
      The attributes will not be stored in the Spotlight index.
      This is useful to test Spotlight import plug-ins.
    • -d level, Print debugging information. This requires -t.
    • -d1, print summary of test import
    • -d2, print summary of import and all attributes, except kMDItemTextContent
    • -d3, print summary of import and all attributes
    • -o outfile, Store attribute into outfile.
      This requires -t.
    • -p, Print out performance information gathered during the run. This requires -t.
    • -A, Print out the list of all of the attributes and their localizations in the current language and exit.
    • -X, Print the schema file and exit.
    • -L, Print the list of installed importers and exit.
    • -r
      Ask the server to reimport files for UTIs claimed by the listed plugin.
      For example, the following would cause all of the chat files on the system to be reimported:
    $ mdimport -r /System/Library/Spotlight/Chat.mdimporter
    
    • 1

    NOTES

    • -f
      is obsolete in Leopard and beyond.

    xargs

    NAME
    xargs – construct argument list(s) and execute utility

    SYNOPSIS
    xargs [-0oprt] [-E eofstr] [-I replstr [-R replacements] [-S replsize]] [-J replstr] [-L number] [-n number [-x]] [-P maxprocs] [-s size] [utility [argument …]]

    DESCRIPTION
    The xargs utility reads space, tab, newline and end-of-file delimited strings from the standard input and executes utility with the strings as arguments.

    Any arguments specified on the command line are given to utility upon each invocation, followed by some number of the arguments read from the standard input of xargs.
    This is repeated until standard input is exhausted.

    Spaces, tabs and newlines may be embedded in arguments using single (') or double (") quotes or backslashes (`) .
    Single quotes escape all non-single quote characters, excluding newlines, up to the matching single quote. Double quotesescape all non-double quote characters, excluding newlines, up to the matching double quote. Any single character, including newlines, may be escaped by a backslash.


    The options are as follows:

    • -0, Change xargs to expect NUL (\0) characters as separators, instead of spaces and newlines.
      This is expected to be used in concert with the -print0 function in find(1).
    • -E eofstr, Use eofstr as a logical EOF marker.
    • -I replstr, Execute utility for each input line, replacing one or more occurrences of replstr in up to replacements (or 5 if no -R flag is specified) arguments to utility with the entire line of input.
      The resulting arguments, after replacement is done, will not be allowed to grow beyond replsize (or 255 if no -S flag is specified) bytes; this is implemented by concatenating as much of the argument containing replstr as possible, to the constructed arguments to utility, up to replsize bytes.
      The size limit does not apply to arguments to utility which do not contain replstr, and furthermore, no replacement will be done on utility itself. Implies -x.
    • -J replstr, If this option is specified, xargs will use the data read from standard input to replace the first occurrence of replstr instead of appending that data after all other arguments.
      This option will not affect how many arguments will be read from input (-n), or the size of the command(s) xargs will generate (-s).
      The option just moves where those arguments will be placed in the command(s) that are executed.
      The replstr must show up as a distinct argument to xargs. It will not be recognized if, for instance, it is in the middle of a quoted string. Furthermore, only the first occurrence of the replstr will be replaced. For example, the following command will copy the list of files and directories which start with an uppercase letter in the current directory to destdir:

    /bin/ls -1d [A-Z]* | xargs -J % cp -Rp % destdir


    • -L number
      Call utility for every number non-empty lines read.
      A line ending with a space continues to the next non-empty line.
      If EOF is reached and fewer lines have been read than number then utility will be called with the available lines.
      The -L and -n options are mutually-exclusive; the last one given will be used.
    • -n number, Set the maximum number of arguments taken from standard input for each invocation of utility.
      An invocation of utility will use less than number standard input arguments if the number of bytes accumulated (see the -s option) exceeds the specified size or there are fewer than number arguments remaining for the last invocation of utility. The current default value for number is 5000.
    • -o, Reopen stdin as /dev/tty in the child process before executing the command.
      This is useful if you want xargs to run an interactive application.
    • -P maxprocs, Parallel mode: run at most maxprocs invocations of utility at once. If maxprocs is set to 0, xargs will run as many processes as possible.
    • -p, Echo each command to be executed and ask the user whether it should be executed.
      An affirmative response, y in the POSIX locale, causes the command to be executed, any other response causes it to be skipped.
      No commands are executed if the process is not attached to a terminal.
    • -r, Compatibility with GNU xargs.
      The GNU version of xargs runs the utility argument at least once, even if xargs input is empty, and it supports a -r option to inhibit this behavior.
      The FreeBSD version of xargs does not run the utility argument on empty input, but it supports the -r option for command-line compatibility with GNU xargs, but the -r option does nothing in the FreeBSD version of xargs.
    • -R replacements, Specify the maximum number of arguments that -I will do replacement in.
      If replacements is negative, the number of arguments in which to replace is unbounded.
    • -S replsize, Specify the amount of space (in bytes) that -I can use for replacements. The default for replsize is 255.
    • -s size, Set the maximum number of bytes for the command line length provided to utility. The sum of the length of the utility name, the arguments passed to utility (including NULL terminators) and the current environment will be less than or equal to this number.
      The current default value for size is ARG_MAX - 4096.
    • -t, Echo the command to be executed to standard error immediately before it is executed.
    • -x, Force xargs to terminate immediately if a command line containing number arguments will not fit in the specified (or default) command line length.

    If utility is omitted, echo(1) is used.

    Undefined behavior may occur if utility reads from the standard input.

    The xargs utility exits immediately (without processing any further input) if a command line cannot be assembled, utility cannot be invoked, an invocation of utility is terminated by a signal, or an invocation of utility exits with a value of 255, the xargs utility stops processing input and exits after all invocations of utility finish processing.


    LEGACY DESCRIPTION
    In legacy mode, the -L option treats all newlines as end-of-line, regardless of whether the line is empty or ends with a space. In addition, the -L and -n options are not mutually-exclusive.

    For more information about legacy mode, see compat(5).


    EXIT STATUS
    The xargs utility exits with a value of 0 if no error occurs. If utility cannot be found, xargs exits with a value of 127, otherwise if utility cannot be executed, xargs exits with a value of 126. If any other error occurs, xargs exits with a value
    of 1.


  • 相关阅读:
    Python和Tensorboard的下载和安装
    大数据课程L2——网站流量项目的算法分析&&数据处理
    [Spring笔记] Spring-32-AOP切入点表达式
    linux __ctype_b_loc
    Nginx之客户并发数限制解读
    Vuex状态管理最佳实践
    一行代码让页面变成黑白
    【iOS】——知乎日报第一周总结
    上周热点回顾(6.17-6.23)
    如何禁止WordPress主题纯英文评论教程
  • 原文地址:https://blog.csdn.net/lovechris00/article/details/125406449