Home > Enterprise >  Remove all except one file in bash on mac
Remove all except one file in bash on mac

Time:03-23

bash on mac, installed by brew

λ  brew list | grep bash
bash

λ  which bash
/usr/local/bin/bash
λ  rm !("shorturl.api")
-bash: !: event not found
λ  ls -1 | grep -v shorturl.api | xargs rm
rm: cannot remove ''$'\033''[0m'$'\033''[01;32mapi'$'\033''[0m': No such file or directory
rm: cannot remove ''$'\033''[01;34metc'$'\033''[0m': No such file or directory
rm: cannot remove ''$'\033''[01;34minternal'$'\033''[0m': No such file or directory
rm: cannot remove ''$'\033''[00mshorturl.go'$'\033''[0m': No such file or directory

CodePudding user response:

The !(pattern-list) globbing pattern only works when extended globbing is enabled. See the extglob section in glob - Greg's Wiki. In this case you need:

shopt -s extglob
rm -- !(shorturl.api)
  • The -- with rm is to prevent files whose names begin with - being treated as options.

One way to do it without extended globbing is:

find . -maxdepth 1 -type f ! -name shorturl.api -delete

The ls -1 | grep -v shorturl.api | xargs rm attempt in the question is broken in several ways, including:

  • The output of ls is intended for reading by humans. It is not suitable for automatic processing. See Why you shouldn't parse the output of ls(1).
  • The grep -v shorturl.api will exclude files other than the intended one. For instance, old-shorturl.api would be excluded.
  • xargs by default uses spaces and newlines to split its input into arguments. xargs rm won't delete files that have such characters in their names.

CodePudding user response:

thanks @GordonDavisson.

use ls --color before pipeline to xargs

ls -1 --color=never | grep -v shorturl.api | xargs rm -rf
  •  Tags:  
  • bash
  • Related