Delete all but some directories

2013-08-16 212 words 1 min read

I think, like me, you would have faced a lot of situations, where you wanted to delete all the files or directories in a location, leaving only the required files/directories. So, I have a directory containing lots of files/directories and I want to delete most of them except some 5/10 of them, how to I do it.

I finally wrote a small script to do that. First save list of files that you do not want to delete in file called “listnames” and then execute the below script. This will give you the rm commands that you need to execute. If you want you can execute the rm command from the script, but to be able to review, I just have the commands echoed.

#!/bin/bash -
#===============================================================================
#
#          FILE: del_all_logs.sh
#
#         USAGE: ./del_all_logs.sh
#
#   DESCRIPTION:
#
#       OPTIONS: ---
#  REQUIREMENTS: ---
#          BUGS: ---
#         NOTES: ---
#        AUTHOR: Amit Agarwal (aka)
#      REVISION:  ---
#===============================================================================

all_runs=$(echo *)
while read line
do
    all_runs=$(echo $all_runs |sed 's/'"$line"'//')
done 
all_runs=$(echo $all_runs |sed 's/'"$0"'//')
all_runs=$(echo $all_runs |sed 's/'"listnames"'//')
echo rm -rf $all_runs


 

Enhanced by Zemanta

author

Authored By Amit Agarwal

Amit Agarwal, Linux and Photography are my hobbies.Creative Commons Attribution 4.0 International License.

We notice you're using an adblocker. If you like our webite please keep us running by whitelisting this site in your ad blocker. We’re serving quality, related ads only. Thank you!

I've whitelisted your website.

Not now
This website uses cookies to ensure you get the best experience on our website. Learn more Got it