Skip to content

Instantly share code, notes, and snippets.

@junjizhi junjizhi/
Created Dec 15, 2013

What would you like to do?
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
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
You can’t perform that action at this time.