繁体   English   中英

Bash Shell脚本使用mdfind搜索文件

[英]Bash Shell Script to search for files using mdfind

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

我的计划的基本想法:

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

目录是什么样的:

+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个文件匹配,并在结果目录中创建硬链接。

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

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

我看了用于创建符号链接的mdfind没有按预期工作 ; 他们有类似的问题(但没有帮助)。

感谢您帮助......这一直是讨厌我很长一段时间。

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

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

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

Spotlight命令使用文件内容的缓存索引。 我不知道有什么方法可以强迫mdfind不这样做。 蛮力方法是在删除文件后使用mdutil -E清除缓存,但您可能不想这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM