1つ以上のファイル形式を除くすべてのファイルを削除する

1つ以上のファイル形式を除くすべてのファイルを削除する

フォルダ内のすべてのファイルを削除するコマンドを見つけようとしましたが、特定のファイル形式は削除しませんでした。しかし、私は運が悪いようです。私が今まで試したこと:

set extended_glob
rm !(*.dmg)
# this returns zsh:number expected

rm ./^*.dmg
# this returns no matches found 

私が使用しているzshのバージョンはzsh 5.0.2 (x86_64-apple-darwin13.0.1)

答え1

これextended_globオプションは zsh の自己拡張機能を提供します。グローバル文法

setopt extended_glob
rm -- ^*.dmg
rm -- ^*.(dmg|txt)

拡張子のないファイル(例README:)は削除されます。これらのファイルを保持するには、演算子を使用して~一致を制限できます。

setopt extended_glob
rm -- *.*~*.dmg

サブディレクトリのファイルも削除するには、次のようにします。**再帰的なワイルドカードに使用されます。渡す. グローバル予選通常のファイルに一致を制限するか、代わりにすべての非^/ディレクトリ.(シンボリックリンクを含む)と一致するために使用します。 (rm -rこれにより、ディレクトリとすべての内容が削除されたり、ディレクトリにまったく入らないため、役に立ちません。)

rm -- **/^*.(dmg|txt)(.)

設定できますksh_glob獲得したオプションksh 球。否定的なパターンが単語の最後である一般的なケースでは、zshは角かっこをglob修飾子として解析します。(kshエミュレーションモードではこれを行いません)。

setopt ksh_glob
rm -- !(*.dmg|*.txt)
setopt no_bare_glob_qual
rm -- !(*.dmg)

答え2

findシェルの代わりに次のコマンドを使用できます。

find . -mindepth 1 -maxdepth 1 ! -name "*.dmg" -delete

から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.

何らかの理由でそれを行うことができない場合は、次のfind方法zsh(または他のシェル)を使用してこれを実行できます。zshはいzsh、おそらくより簡単な方法があります。しかし、私はbash男なので、次のように思い出しました。

for file in *; do if [[ ! "$file" == *.dmg ]]; then rm $file; fi; done

答え3

ファイルを削除するもう1つの方法はfindxargsおよび次を使用することですrm

find . -mindepth 1 -maxdepth 1 ! -name '*.dmg' -print0 | xargs -0 rm

答え4

find  path -mindepth 1 -maxdepth 1 -type f ! -name "*.dmg" -exec rm -vf {} \;

関連情報