Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@junjizhi
Created December 15, 2013 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junjizhi/7974956 to your computer and use it in GitHub Desktop.
Save junjizhi/7974956 to your computer and use it in GitHub Desktop.
delete file not ending with a certain format
#delete files or dirs whose name does not end with '.sh' in the current path
ls | grep -v '\.sh$' | xargs rm -r
#However, this way does not solve the problem that the path names that have spaces, for example, "cmp\ output"
#more robust version
#from http://stackoverflow.com/questions/4702577/need-a-shell-script-that-deletes-all-files-except-pdf
find . -maxdepth 1 -type f ! -iname '*.pdf' -delete
#if we need to delete the directories, too, then remove '-type f'
find . -maxdepth 1 ! -iname '*.pdf' -delete
#however, it will not delete the non-empty directories
find . -maxdepth 1 ! -iname '*.sh' -exec rm -r {} \;
#the above command can somehow do the trick, but it will give the warning that "rm: cannot remove directory: ‘.’"
#so to fix that, it should be
find . -maxdepth 1 \( ! -iname '*.sh' ! -iname '.' \) -exec rm -r {} \;
#be careful about the empty spaces in the command
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment