macos - 使用 mdfind 搜索文件的 Bash Shell 脚本

标签 macos bash spotlight ln

我有一个包含大约 350 张图像的文件夹(它们是扫描的食谱)。为了更容易找到它们,我用 bash shell 脚本编写了一个搜索程序。我在 Mac OS X 10.8 Mountain Lion 上安装了 bash 3.2 版。

我的程序的基本思路:

  1. 询问用户搜索词(使用 osascript)。
  2. 使用 mdfind 在文件(名称)中搜索搜索词。
  3. 将匹配的文件发送到 ln(通过 xargs)。
  4. 在“结果”目录中建立匹配文件的硬链接(hard link)。此目录包含在同一图像文件夹中(此目录在程序开始时被清除)。

目录是什么样的:

+Recipes
  -files
  -files
  -files
  +.search
     -search (shell script)
     +results
        -links
        -links

这是我的代码:

#!/bin/bash
#
# Search program for recipes.
# version 2

# Clean out results folder
rm -rf ~/Google\ Drive/Recipes/.search/results/*

# Display the search dialog
query=$(osascript <<-EOF
        set front_app to (path to frontmost application as Unicode text)
        tell application front_app to get text returned of (display dialog "Search     for:" default answer "" with title "Recipe Search")
EOF)

# If query is empty (nothing was typed), exit
if [ "$query" = "" ]
then
    exit
fi

echo "Searching for \"$query\"."

# Search for query and (hard) link. The output from 'ln -v' is stored in results
# 'ln' complains if you search for the same thing twice... mdfind database lagging?
results=$(mdfind -0 -onlyin ~/Google\ Drive/Recipes/ "$query" | xargs -0 -J % ln -fv % ~/Google\ Drive/Recipes/.search/results)

if [ "$results" ]
then
    # Results were found, open the folder
    open ~/Google\ Drive/Recipes/.search/results/
else
    # No results found, display a dialog
    osascript <<-EOF
        beep
        set front_app to (path to frontmost application as Unicode text)
        tell application front_app to display dialog "No results found for \"" & "$query" & "\"." buttons "Close" default button 1 with icon 0
    EOF
fi

它运行良好——第一次。如果您两次搜索相同的内容,它就会崩溃。

解释:假设我搜索“鸡”。匹配34个文件,在结果目录下做硬链接(hard link)。

现在,我再次运行程序,搜索相同的东西——“鸡”。该目录被清空(通过 rm)。但是现在,查找/链接停止工作了——只有 6 或 7 个食谱将被链接。似乎正在发生的事情是 mdfind 正在搜索目录中找到结果,在它们被删除之后,然后 ln 不能建立联系。但它没有找到主要文件...... 我明白了

ln: ~/Google Drive/Recipes/.search/results/recipe.jpg: no such file or directory

我看了mdfind used for creating symlinks not working as expected ;他们有类似的问题(但没有帮助)。

感谢任何的帮助...这让我烦恼了很长时间。

最佳答案

您可以使用 mdimport 重新索引目录或文件。

$ touch aa
$ mdfind -onlyin . -name aa
/Users/lauri/Desktop/aa
$ rm aa
$ mdimport .
$ mdfind -onlyin . -name aa
$ 

Spotlight 不会索引以句点开头的目录,因此您可以重命名 .search 目录。

关于macos - 使用 mdfind 搜索文件的 Bash Shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12169265/

相关文章:

c - 交换到 ucontext_t 的 uc_link 时发生 swapcontext 段错误

objective-c - 如何获得类似于 Spotlight 或 iTunes 的搜索功能?

php - 如何在 mac os 中安装 phalcon.so

macos - 如何获得 zipalign for mac?

bash - 在 bash 中,函数内部的 heredoc 返回语法错误

regex - sed 命令在 solaris 中不能正常工作但在 linux 中工作

spotlight - OS X Yosemite Spotlight 扩展

Cocoa/Objective-C - 具有文本输入的子窗口,主窗口不会变为非事件状态

swift - 如何删除一些被 Xcode 复制的 Swift 库?

bash - 在 Ubuntu 中将 mahout 添加到路径