我一直试图找到一个命令来删除文件夹中的所有文件,但不是一种文件类型。但我似乎没有任何运气。到目前为止我尝试过的:
set extended_glob
rm !(*.dmg)
# this returns zsh:number expected
rm ./^*.dmg
# this returns no matches found
Run Code Online (Sandbox Code Playgroud)
我使用的 zsh 版本是zsh 5.0.2 (x86_64-apple-darwin13.0.1).
Gil*_*il' 24
该extended_glob选项为您提供 zsh 自己的扩展glob 语法。
setopt extended_glob
rm -- ^*.dmg
rm -- ^*.(dmg|txt)
Run Code Online (Sandbox Code Playgroud)
您可以设置ksh_glob选项以获取ksh globs。请注意,在否定模式是单词中最后一个事物的常见情况下,zsh 可能会将括号解析为 glob 限定符(在 ksh 仿真模式下不会这样做)。
setopt ksh_glob
rm -- !(*.dmg|*.txt)
setopt no_bare_glob_qual
rm -- !(*.dmg)
Run Code Online (Sandbox Code Playgroud)
您可以使用find代替您的外壳:
find . -mindepth 1 -maxdepth 1 ! -name "*.dmg" -delete
Run Code Online (Sandbox Code Playgroud)
来自man find:
! expr True if expr is false. This character will also usually need
protection from interpretation by the shell.
-name pattern
Base of file name (the path with the leading directories removed)
matches shell pattern pattern.
-delete
Delete files; true if removal succeeded. If the removal failed,
an error message is issued. If -delete fails, find's exit status
will be nonzero (when it eventually exits). Use of -delete
automatically turns on the -depth option.
Run Code Online (Sandbox Code Playgroud)
如果您find因任何原因无法使用,这里有一种使用zsh(或其他外壳)的方法。zsh正在zsh,可能有一种更简单的方法来做到这一点,但由于我是一个bash男人,这就是我想出的:
for file in *; do if [[ ! "$file" == *.dmg ]]; then rm $file; fi; done
Run Code Online (Sandbox Code Playgroud)