Thursday, February 17, 2011

Bash delete directories except that one

Ran into a scenario where I needed to delete all subdirectories of target except target/keepme/. So I want rm -rf target/subdir1 target/subdir2 ... target/subdirN with one directory omitted. I want to use grep to remove the directory I want to keep from the list so something like this should work:


  1. Print the list of directories echo target/*/
  2. Flip space separator to newline  tr " " "\n"
  3. Remove the line for the directory to keep grep -v keepme
  4. Flip newline back to space  tr "\n" " "
  5. Run rm -rf on the results from steps 1-4

As a 1-liner:

rm -rf $(echo target/*/ | tr " " "\n" | grep -v keepme | tr "\n" " ")

Noting it in case I need to do it again someday ;)

2 comments:

Kamran Zafar said...

How about this one:

find target/* ! -iname keepme -print0 | xargs -0 rm -rf

this works for me

Naviya Nair said...

I have read your blog its very attractive and impressive. I like it your blog.

Java Online Training Java EE Online Training Java EE Online Training Java 8 online training Core Java 8 online training

Java Online Training from India Java Online Training from India Core Java Training Online Core Java Training Online Java Training InstitutesJava Training Institutes

Post a Comment