【问题标题】:Searching for hundreds of files on a server在服务器上搜索数百个文件
【发布时间】:2018-08-03 16:22:25
【问题描述】:

我有一个包含 577 个图像文件的列表,我需要在大型服务器上搜索这些文件。我不是 bash 方面的专家,所以我自己能做的最好的就是 577 行:

find /source/directory -type f -iname "alternate1_1052956.tif" -exec cp {} /dest/directory \;

...为每个文件名重复这一行。它可以工作...但它令人难以置信很慢,因为它会在整个服务器中搜索一个文件,然后转到下一行,但每次搜索可能需要 20 分钟。我一夜之间离开了,到早上才发现其中的 29 个,这太慢了。以这样的速度可能需要两周时间才能找到所有这些。

我尝试使用 -o 作为 OR 分隔符分隔每一行,希望它会搜索一次 577 个文件,但我无法让它工作。

有人有什么建议吗?我还尝试使用我拥有的文件名的 .txt 文件作为搜索的基础,但也无法让它工作。不幸的是,我没有这些文件的路径,只有基本名称。

【问题讨论】:

  • 制作一份服务器上所有文件的列表,从该列表中 grep 577 个文件,创建一个 for 循环将这些文件复制到您想要的位置。
  • 为什么-o -iname 不适合你?

标签: bash macos shell terminal


【解决方案1】:

如果要复制所有.tif 文件

find /source/directory -type f -name "*.tif" -exec cp {} /dest/directory \;
#                                     ^

【讨论】:

  • 这里只有正则表达式
  • 不行,我需要搜索具体的文件名。有数十万张图片,我需要其中的 577 张。
【解决方案2】:

在 MacOS 上,使用 mdfind 命令在 SpotLight 索引中查找文件名。这非常快,因为它只是一个索引查找,就像 Linux 中的 locate 命令一样:

cp $(mdfind alternate1_1052956.tif) /dest/directory

如果您在一个文件中拥有所有文件名(每个文件一行),请使用 xargs

xargs -L 1 -I {} cp $(mdfind {}) /dest/directory < file_with_list 

【讨论】:

  • 我试过你的xargs,我认为问题在于我没有指定源目录是什么。我 CD 到我要搜索的目录,然后运行它,但它开始从 /Library/Applications 和其他各种随机位置复制文件。我拥有的文件列表不包括路径,只包括基本名称,所以我有办法指定源目录吗?
【解决方案3】:

创建一个包含所有文件名的文件,然后编写一个循环遍历该文件并在后台执行命令。

请注意,这将占用大量内存,因为您将同时执行多次。因此,请确保您有足够的内存。

while read -r line; do
find /source/directory -type f -iname "$line" -exec cp {} /dest/directory \ &;
done < input.file

【讨论】:

    【解决方案4】:

    在这个答案中有一些假设。你有一个所有577 文件名的列表,我们称之为inputfile.list。文件名中没有空格。以下可能有效:

    $ cat findcopy.sh
    #!/bin/bash
    
    cmd=$(
    echo -n 'find /path/to/directory -type f '
    readarray -t filearr < inputfile.list  # Read the list to an array
    n=0
    for f in "${filearr[@]}" # Loop over the array and print -iname 
    do
        (( n > 0 )) && echo "-o -iname ${f}"  || echo "-iname ${f}"
        ((n++))
    done
    echo -n ' | xargs -I {} cp {} /path/to/destination/'
    )
    eval $cmd 
    

    执行:./findcopy.sh

    注意MacOS。它没有readarray。而是使用任何其他简单的方法将列表输入数组,例如,

    filearr=($(cat inputfile.list))
    

    【讨论】:

    • 我试了一下。我收到错误line 15: readarray: command not found,我相信指的是最后一行。这确实复制了文件,但它开始从 /dest 复制所有文件,而不是在列表中搜索特定文件。
    • 没有意识到你有一个MacOSX。请参阅我的更新说明。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多