bash根据内容删除目录

时间:2011-07-22 06:55:53

标签: bash directory file-manipulation

目前我有多个目录

Directory1 Directory2 Directory3 Directory4

这些目录中的每一个都包含文件(这些文件有点神秘)

我想要做的是扫描文件夹中的文件以查看是否存在某些文件,如果它们是单独保留该文件夹,如果某些文件不存在则只删除整个目录。这就是我的意思:

即时搜索包含单词.pass的文件。在文件名中。 Say Directory 4有我正在寻找的文件

Direcotry4:    
file1.temp.pass.exmpl
file1.temp.exmpl
file1.tmp

并且其他目录没有该特定文件:

file.temp
file.exmp
file.tmp.other

所以我想删除Directory1,2和3但只保留目录4 ......

到目前为止,我已经提出了这个代码

(arr是所有目录名称的数组)

for x in ${arr[@]}
do
    find $x -type f ! -name "*pass*" -exec rd {} $x\;
done

我想到这样做的另一种方式是这样的:

for x in ${arr[@]}
do

    cd $x find . -type f ! -name "*Pass*" | xargs -i rd {} $x/
done

到目前为止,这些似乎不起作用,我害怕我可能做错了,并删除了所有文件.....(我已经备份)

有什么方法可以做到这一点吗?记得我希望目录4不变,我要保留其中的所有内容

2 个答案:

答案 0 :(得分:2)

查看您的目录是否包含传递文件:

if [ "" = "$(find directory -iname '*pass*' -type f |  head -n 1)" ]
  then
    echo notfound
  else
    echo found
fi

要在循环中执行此操作:

for x in "${arr[@]}"
  do
      if [ "" = "$(find "$x" -iname '*pass*' -type f |  head -n 1)" ]
        then
          rm -rf "$x"
      fi
  done

答案 1 :(得分:1)

试试这个:

# arr is a array of all the directory names
for x in ${arr[@]}
do
ret=$(find "$x" -type f -name "*pass*" -exec echo "0" \;)
# expect zero length $ret value to remove directory
if [ -z "$ret" ]; then
    # remove dir
    rm -rf "$x"
fi
done