mco*_*awc 2 command-line scripts zsh rm
我和这个问题有同样的问题如何从文件夹中删除除少数文件夹之外的所有文件/文件夹?几次。这就是我想为命令 rmnot 自己编写脚本的原因。如有必要,即使使用通配符,它也应该使用任意数量的文件,并删除同一目录中除这些文件之外的任何内容(非递归)。典型的例子是:
rmnot *tex *bib *png
Run Code Online (Sandbox Code Playgroud)
我的脚本可以工作,但是由于我没有经验并且想以正确的方式学习它,有没有更优雅的方法来编写这个脚本?
#!/bin/zsh
insert="-name . -or -name .."
for i in {1..$#}; do
insert="$insert -or -name ${(P)i}"
done
insert="\( $insert \)"
eval "find -not $insert -exec rm {} \;"
Run Code Online (Sandbox Code Playgroud)
PS:我必须使用 ZSH,因为${(P)i}我认为其他任何东西都可以在 bash 中使用。
======优化版本======
#!/bin/bash
insert="-name . -or -name .."
for i; do
insert="$insert -or -name $i"
done
insert="\( $insert \)"
find -maxdepth 1 -not $insert -delete
Run Code Online (Sandbox Code Playgroud)
ter*_*don 10
你甚至不需要脚本。如果您使用 bash,您可以打开extglob并给出否定模式:
$ ls
foo.avi foo.bbl foo.bib foo.log foo.png foo.tex foo.txt foo.wav
$ shopt -s extglob
$ rm !(*tex|*bib|*png)
$ ls
foo.bib foo.png foo.tex
Run Code Online (Sandbox Code Playgroud)
如中所述man bash:
If the extglob shell option is enabled using the shopt builtin, several
extended pattern matching operators are recognized. In the following
description, a pattern-list is a list of one or more patterns separated
by a |. Composite patterns may be formed using one or more of the fol?
lowing sub-patterns:
?(pattern-list)
Matches zero or one occurrence of the given patterns
*(pattern-list)
Matches zero or more occurrences of the given patterns
+(pattern-list)
Matches one or more occurrences of the given patterns
@(pattern-list)
Matches one of the given patterns
!(pattern-list)
Matches anything except one of the given patterns
Run Code Online (Sandbox Code Playgroud)
随着zsh,等效是:
setopt extended_glob
rm ^(*tex|*bib|*png)
Run Code Online (Sandbox Code Playgroud)
如果您仍然想为此编写脚本,只需连接您提供的参数,但不要使用通配符 ( *),让脚本添加它们(感谢@Helios 提出更简单的版本):
$ ls
foo.avi foo.bbl foo.bib foo.log foo.png foo.tex foo.txt foo.wav
$ shopt -s extglob
$ rm !(*tex|*bib|*png)
$ ls
foo.bib foo.png foo.tex
Run Code Online (Sandbox Code Playgroud)