【问题标题】:How to delete all files and folders that are not image in a folder?如何删除文件夹中所有不是图像的文件和文件夹?
【发布时间】:2016-08-19 21:49:20
【问题描述】:

您知道如何删除所有非图像文件(.png、.jpg 等)和所有不包含图像文件的文件夹吗?

通过命令行或者shell脚本,可以吗?

注意:我使用的是 Mac 终端

【问题讨论】:

  • 你可以使用find,看看这个post,但记得显示你到目前为止尝试了什么。

标签: bash macos shell terminal find


【解决方案1】:

您可以先find all files that are not .png or .jpg 删除它们。然后,遍历所有目录并尝试将它们全部删除。只有那些为空的才会被删除:

find -type f ! -regex ".*\.\(jpg\|png\)" -delete
find -type d -delete

在 Mac OS X 上,you can't use \| in a basic regular expression,这是 find 默认使用的。所以如果第一个表达式对你不起作用,use the -o flag:

find . -type f ! \( -name "*.jpg" -o -name "*.png" \) -delete

鉴于此结构:

$ 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

现在让我们删除目录:

$ 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

【讨论】:

  • 如果是图形文件最好使用文件魔法来解决
  • @Vorsprung 很有趣。某种file -ib <file>,如果输出包含image
  • 找到 . -类型 f ! -regex ".*\.(jpg\|png)" -delete ----> 删除所有文件
  • @chipbk10 您可能需要 -E 标志 --> find -E -type f ! -regex ".*\.\(jpg\|png\)"。测试它,如果它显示需要什么,然后添加-delete
  • @chipbk10 那你可能需要find . -type f ! \( -name "*.jpg" -o -name "*.png" \)
【解决方案2】:
真=0 假=1 是空的() { 如果 ["$(ls -A $1)" ];然后 返回 $false 菲 返回 $true } del_img() { 本地我 对于 i in "$1"/*;做 # 文件:不是 png、jpg 和我们的 shell 脚本 if [ -f "${i}" ] && [[ "${i}" != *.png ]] && [[ "${i}" != *.jpg ]] && [[ "${i }" != *.sh ]];然后 echo "remove ".$(basename "${i}") rm "${i}" 菲 # 文件夹:访问里面 如果 [ -d "${i}" ];然后 del_img "${i}" 菲 # 文件夹:如果为空则删除 if [ -d "${i}" ] && is_empty "${i}";然后 echo "remove ".$(basename "${i}") rmdir "${i}" 菲 完毕 } del_img $密码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多