如何仅删除本身仅包含进一步命名的子目录的子目录?
How do I remove only sub-directories that themselves only contain a further named sub-directory?
我在 Debian 机器上有一个包含多个子目录的数据目录,当系统处理了一个子目录的内容时,它会在其中添加一个子目录“.processed”。
不幸的是,当数据被删除时,“.processed”目录被留下,我必须手动删除它们,在仍然包含数据的目录中。
有没有办法只删除仅包含目录“.processed”而没有其他文件或目录的子目录?
您可以使用这个 shell 脚本:
#!/bin/bash
find . -type d -print | tac | while read -r file ; do
if [[ "$(ls -A "$file")" = ".processed" ]];
then
rmdir "$file"/".processed"
rmdir "$file"
fi
done
此脚本在脚本中 find . -type d
. If it discovers a directory containing only a directory named .processed
, then it delete the .processed
directory and the directory containing it. Only empty directories are removed, so the script use rmdir
. In general, try to avoid using rm -rf
给出的所有目录上循环,因为它可能很危险...
如果要删除的目录顺序是将子目录放在目录之前,则 rmdir
will fail. Using rm -rf *
solves the issue but is dangerous. The solution here is to pipe to tac
and reverse the order given by find
.
该脚本在文件名中使用空格。感谢 Sorpigal answer, named pipe to while, newline terminated 的解决方案。
我在 Debian 机器上有一个包含多个子目录的数据目录,当系统处理了一个子目录的内容时,它会在其中添加一个子目录“.processed”。
不幸的是,当数据被删除时,“.processed”目录被留下,我必须手动删除它们,在仍然包含数据的目录中。
有没有办法只删除仅包含目录“.processed”而没有其他文件或目录的子目录?
您可以使用这个 shell 脚本:
#!/bin/bash
find . -type d -print | tac | while read -r file ; do
if [[ "$(ls -A "$file")" = ".processed" ]];
then
rmdir "$file"/".processed"
rmdir "$file"
fi
done
此脚本在脚本中 find . -type d
. If it discovers a directory containing only a directory named .processed
, then it delete the .processed
directory and the directory containing it. Only empty directories are removed, so the script use rmdir
. In general, try to avoid using rm -rf
给出的所有目录上循环,因为它可能很危险...
如果要删除的目录顺序是将子目录放在目录之前,则 rmdir
will fail. Using rm -rf *
solves the issue but is dangerous. The solution here is to pipe to tac
and reverse the order given by find
.
该脚本在文件名中使用空格。感谢 Sorpigal answer, named pipe to while, newline terminated 的解决方案。