开发者

bash delete directories based on contents

Currently I have multiple direc开发者_运维知识库tories

Directory1 Directory2 Directory3 Directory4

each of these directories contain files (the files are somewhat cryptic)

what i wish to do is scan files within the folders to see if certain files are present, if they are then leave that folder alone, if the certain files are not present then just delete the entire directory. here is what i mean:

im searching for the files that have the word .pass. in the filename. Say Directory 4 has that file that im looking for

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

and the rest of the Directories do not have that specific file:

file.temp
file.exmp
file.tmp.other

so i would like to delete Directory1,2 and3 But only keep Directory 4...

So far i have come up with this code

(arr is a array of all the directory names)

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

another way i have thought of doing this is like this:

for x in ${arr[@]}
do

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

SO far these don't seem to work, and im scared that i might do something wrong and have all my files deleted.....(i have backed up)

is there any way that i can do this? remember i want Directory 4 to be unchanged, everything in it i want to keep


To see if your directory contains a pass file:

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

To do that in a loop:

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


Try this:

# 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜