Search code examples
linuxunixrm

How to remove all folders except a few mentioned one in linux


I have the following folder structure inside my wp-content folder =>

2016/ => it has many subfolders in it and I wanna keep them
2015/ => it has many subfolders in it and I wanna keep them
2014/ => it has many subfolders in it and I wanna keep them
2013/ => it has many subfolders in it and I wanna keep them

besides those folder there are tons of temp folders which I want to delete along with anything inside it. The folder name look like this:

ZhsvhgTjh/
Vgfsugu79/
1agDjgdki/
8gdygREfh/
Hbjddsyug/
....so on....

Now the problem is if I run rm -f then it is gonna remove everything inside that folder, including the folders like 2016, 2015, 2014, 2013.

Also if I try the following: find . -name a -exec rm -rf {} \; then it will only work for 1 folder name and I have type each random folder name which is insane as it has almmost 20,000+ temp folders.

So, I was hoping if anyone can help me with a command using which I can remove all the folders and contents within it except the 2016, 2015, 2014, 2013 folders and their contents.

Also as this a remove command can anyone let me know if there is a way I can run a count command to see if the query is selecting the right number of folders or not? I don't wanna delete any important stuffs accidentally.

Thank you.


Solution

  • Print tree

    prodrive11@raccoon:~/tmpp/wp-content$ ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'
       .
       |-2015
       |---keep2
       |---keep3
       |-2016
       |---keep1
       |---keep2
       |-NKAXOIND
       |-x232sfsw
       |---we233ds
    

    Show garbage folders:

       prodrive11@raccoon:~/tmpp/wp-content$ find . -type d | grep -Pv '20\d{2}' | tail -n +2                   ./x232sfsw
        ./x232sfsw/we233ds
        ./NKAXOIND
    

    Count them

    prodrive11@raccoon:~/tmpp/wp-content$ find . -type d | grep -Pv '20\d{2}' | tail -n +2 | wc -l
    3
    

    Remove them

    prodrive11@raccoon:~/tmpp/wp-content$ find . -type d | grep -Pv '20\d{2}' | tail -n +2 | xargs rm -rf
    

    Show tree again

    prodrive11@raccoon:~/tmpp/wp-content$ ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'
       .
       |-2015
       |---keep2
       |---keep3
       |-2016
       |---keep1
       |---keep2