Bash 如何删除文件夹中不包含图像的所有文件和文件夹?
您知道如何删除所有非图像文件(.png、.jpg等)的文件以及所有不包含图像文件的文件夹吗 通过命令行或shell脚本,可以吗 注意:我正在使用Mac终端您可以先删除它们。然后,遍历所有目录并尝试将它们全部删除。只有空的才会被删除:Bash 如何删除文件夹中不包含图像的所有文件和文件夹?,bash,macos,shell,terminal,find,Bash,Macos,Shell,Terminal,Find,您知道如何删除所有非图像文件(.png、.jpg等)的文件以及所有不包含图像文件的文件夹吗 通过命令行或shell脚本,可以吗 注意:我正在使用Mac终端您可以先删除它们。然后,遍历所有目录并尝试将它们全部删除。只有空的才会被删除: find -type f ! -regex ".*\.\(jpg\|png\)" -delete find -type d -delete 在Mac OS X上,默认情况下,find会使用它。因此,如果第一个表达式对你不起作用 鉴于这种结构: $ tree .
find -type f ! -regex ".*\.\(jpg\|png\)" -delete
find -type d -delete
在Mac OS X上,默认情况下,find
会使用它。因此,如果第一个表达式对你不起作用
鉴于这种结构:
$ tree
.
├── a1
│ └── a.png
├── a2
│ ├── b.jpg
│ └── b.png
└── a3
├── a.txt
└── b.txt
3 directories, 5 files
以下是要删除的文件:
$ find -type f ! -regex ".*\.\(jpg\|png\)"
./a3/b.txt
./a3/a.txt
那么让我们开始吧:
$ find -type f ! -regex ".*\.\(jpg\|png\)" -delete
现在让我们删除dir:
$ find -type d -delete
find: cannot delete `./a1': Directory not empty
find: cannot delete `./a2': Directory not empty
因此,我们最终拥有:
$ tree
.
├── a1
│ └── a.png
└── a2
├── b.jpg
└── b.png
2 directories, 3 files
真=0
false=1
是空的吗
{
如果[“$(ls-A$1)”],则
返回$false
fi
返回$true
}
del_img()
{
本地i
对于“$1”/*”中的i;请
#文件:不是png、jpg和我们的shell脚本
如果[-f“${i}]”和&[“${i}”!=*.png]]和&[“${i}”!=*.jpg]]和&[“${i}”!=*.sh]];那么
echo“remove”。$(basename“${i}”)
rm“${i}”
fi
#文件夹:访问内部
如果[-d“${i}”];则
del_img“${i}”
fi
#文件夹:如果为空,请删除
如果[-d“${i}”]&&u为空“${i}”;则
echo“remove”。$(basename“${i}”)
rmdir“${i}”
fi
完成
}
del_img$PWD
你可以使用find,看看这个,但是记住展示你到目前为止尝试过的东西。最好使用文件魔术来计算它是否是一个图形file@Vorsprung有趣的某种类型的
文件-ib
,如果输出包含图像
,请查找-f型-正则表达式“*\(jpg\ | png)”-删除-->它删除所有files@chipbk10可能您需要-E标志-->find-E-typef-正则表达式“*\。\(jpg\| png\)”
。测试它,如果它显示需要什么,然后添加-delete
@chipbk10,那么您可能需要查找-f型\(-name“*.jpg”-o-name“*.png”\)
。
$ tree
.
├── a1
│ └── a.png
└── a2
├── b.jpg
└── b.png
2 directories, 3 files
true=0
false=1
is_empty()
{
if [ "$(ls -A $1)" ]; then
return $false
fi
return $true
}
del_img()
{
local i
for i in "$1"/*; do
# file: not png, jpg and our shell script
if [ -f "${i}" ] && [[ "${i}" != *.png ]] && [[ "${i}" != *.jpg ]] && [[ "${i}" != *.sh ]]; then
echo "remove ".$(basename "${i}")
rm "${i}"
fi
# folder: access inside
if [ -d "${i}" ]; then
del_img "${i}"
fi
# folder: remove if empty
if [ -d "${i}" ] && is_empty "${i}"; then
echo "remove ".$(basename "${i}")
rmdir "${i}"
fi
done
}
del_img $PWD