【问题标题】:List directories not containing certain files?列出不包含某些文件的目录?
【发布时间】:2012-10-13 14:02:40
【问题描述】:

我用这个命令找到了当前目录下所有包含.mp3的目录,只过滤掉了目录名:

find . -iname "*.mp3" | sed -e 's!/[^/]*$!!' -e 's!^\./!!' | sort -u

我现在想要相反,但我发现它有点难。我不能只添加一个“!”到 find 命令,因为它只会在打印时排除 .mp3,而不是查找不包含 .mp3 的目录。

我用谷歌搜索了这个并在 stackoverflow 和 unix.stackexchange.com 上进行了搜索。 到目前为止,我已经尝试过这个脚本,它返回这个错误:

#!/bin/bash

find . -type d | while read dir
do
if [[! -f $dir/*.mp3 ]]
then
    echo $dir
fi
done

/home/user/bin/try.sh: 第 5 行: [[!: command not found

#!/bin/bash

find . -type d | while read dir
do
if [! -f $dir/*.mp3 ]
then
    echo $dir
fi
done

/home/user/bin/try.sh: 第 5 行: [!: command not found

#!/bin/bash

find . -type d | while read dir
do
if [[! -f "$dir/*.mp3" ]]
then
    echo $dir
fi
done

/home/user/bin/try.sh: 第 5 行: [!: command not found

我认为这与 test 命令的多个参数有关。

由于我正在测试变量将要更改的所有目录,因此我使用通配符作为文件名。

非常感谢任何帮助。谢谢。

【问题讨论】:

标签: bash shell testing wildcard


【解决方案1】:
[ "$(echo $dir/*.mp3)" = "$dir/*.mp3" ]

应该可以。

或者只是在'['和'!'之间添加一个空格

一种可能明显更快的方法是

if find "$dir" -name '*.mp3' -quit ; then
  : # there are mp3-files in there.
else
  ; # no mp3:s
fi

【讨论】:

  • [! 之间添加一个空格可以修复直接错误,但在包含多个 .mp3 文件的目录中测试仍然会失败。 echo 方法效果更好(尽管它仍然可能在包含一个具有确切名称 *.mp3 的单个 .mp3 的目录上失败)。
  • 如果有多个扩展需要测试,find 解决方案也可以更好地扩展。
  • 感谢您的回复。我用空格进行了更改,但即使里面没有mp3,它仍然返回目录的名称。
【解决方案2】:

好的,我用计数器解决了我自己的答案。

我不知道它的效率如何,但它确实有效。我知道它可以做得更好。欢迎批评指正。

find . -type d | while read dir
do
count=`ls -1 "$dir"/*.mp3 2>/dev/null | wc -l`
    if [ $count = 0 ]
    then
        echo $dir
    fi
done

这将打印所有不包含 MP3 的目录。由于 find 命令递归打印目录,它还显示子目录。

【讨论】:

    【解决方案3】:

    我运行了一个脚本来自动下载我的 mp3 收藏的封面。它在每个专辑的目录中放置一个名为“cover.jpg”的文件,它可以检索到它的艺术作品。我需要检查脚本失败的专辑 - 即哪些 CD(目录)不包含名为 cover.jpg 的文件。这是我的努力:

    find . -maxdepth 1 -mindepth 1 -type d | while read dir; do [[ ! -f $dir/cover.jpg ]] && echo "$dir has no cover art"; done
    

    maxdepth 1 阻止 find 命令下降到我的 WD My Cloud NAS 服务器为每个专辑创建并放置默认通用光盘映像的隐藏目录。 (这在下一次扫描中被清除。)

    编辑:cd 到 MP3 目录并从那里运行它,或者更改 .在上面的命令中指向它的路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-06
      • 2017-04-13
      • 2021-03-30
      • 1970-01-01
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多