Asuming your exclude.txt
looks like this:
leaveme.jpg
i am staying.gif
james/leaveme.gif
and all sub-directories and files are located in one parent directory and your exclude.txt
along with the delete.sh
are located outside that parent directory.
The script below will do the following:
- Read file names from
exclude.txt
line by line.
- Find all matching file names under the parent directory and mark them by adding
.KEEP
suffix to them.
- Find all files under the parent directory that are not marked with the
.KEEP
suffix and delete them.
- Find all empty sub-directories under the parent directory and delete them.
- Remove the
.KEEP
suffix from the kept files returning them to their original names.
!!! WARNING: THIS IS NOT A DRY RUN !!!
When run, the script will do all the above actions immediately. Do not run it on your actual directory until you test it first to see if the results are what you want.
To test the script first, run it on a fake copy directory similar in structure and naming to your desired directory.
You can also see what files will be deleted first before actually deleting them by changing this line:
find "$path" -type f ! -name "*.KEEP" -exec rm {} \;
with this line:
find "$path" -type f ! -name "*.KEEP" -exec echo {} "Will be deleted!" \;
in step 2 below to just print the names of the files to be deleted instead of actually deleting them.
To create and use the script, please follow these steps:
Create and edit a script file in your home directory and name it delete.sh
by running the following command in the terminal:
nano ~/delete.sh
Copy and paste the following code into the editor replacing /path/to/parent/directory/
with the full path of the directory that contains the files to be deleted and replacing /path/to/exclude.txt
with the full path to your exclude.txt
:
#!/bin/bash
path="/path/to/parent/directory/"
filelist="/path/to/exclude.txt"
while IFS=$'\n' read filename
do
mv -n "$path$filename" "$path$filename.KEEP"
done < "$filelist"
find "$path" -type f ! -name "*.KEEP" -exec rm {} \;
find "$path" -type d -empty -delete
while IFS=$'\n' read filename
do
mv -n "$path$filename.KEEP" "$path$filename"
done < "$filelist"
Save the script file and exit the editor by pressing Ctrl + X then press Y.
Make the script file executable by running the following command in the terminal:
chmod +x ~/delete.sh
Run the script by running the following command in the terminal:
bash ~/delete.sh
Done, only the files listed in exclude.txt
are left under your parent directory.