【发布时间】:2016-08-19 21:49:20
【问题描述】:
您知道如何删除所有非图像文件(.png、.jpg 等)和所有不包含图像文件的文件夹吗?
通过命令行或者shell脚本,可以吗?
注意:我使用的是 Mac 终端
【问题讨论】:
-
你可以使用find,看看这个post,但记得显示你到目前为止尝试了什么。
标签: bash macos shell terminal find
您知道如何删除所有非图像文件(.png、.jpg 等)和所有不包含图像文件的文件夹吗?
通过命令行或者shell脚本,可以吗?
注意:我使用的是 Mac 终端
【问题讨论】:
标签: bash macos shell terminal find
您可以先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
【讨论】:
file -ib <file>,如果输出包含image。
find -E -type f ! -regex ".*\.\(jpg\|png\)"。测试它,如果它显示需要什么,然后添加-delete。
find . -type f ! \( -name "*.jpg" -o -name "*.png" \)。
【讨论】: