Home > front end >  removing directory and sub directory which is not present in the list
removing directory and sub directory which is not present in the list

Time:11-10

This is my directory structure

find -type f -print0 | xargs -0 ls -t
./lisst.txt                  ./SAMN03272855/SRR1734376/SRR1734376_1.fastq.gz
./SAMN03272854/SRR1734375/SRR1734375_2.fastq.gz  ./SAMN07605670/SRR6006890/SRR6006890_2.fastq.gz
./SAMN03272854/SRR1734375/SRR1734375_1.fastq.gz  ./SAMN07605670/SRR6006890/SRR6006890_1.fastq.gz
./SAMN03272855/SRR1734376/SRR1734376_2.fastq.gz

So this is a small subset of my folder/files where i have around 70.

I have a made a list of files which i want to keep and other i would like to delete.

My list.txt contains SAMN03272854,SAMN03272855 but I want to remove SAMN07605670.

I ran this

find . ! -name 'lisst.txt' -type d -exec rm -vrf {}  

It removed everything

QUESTION UPDATE

In my list it contains the folder i want to keep and the one which are not there are to be removed.

The folders which are to be removed also contains subdirectories and files. I want to remove everything

CodePudding user response:

Your command selects each directory in the tree, except a directories of the funny name lisst.txt. Once it finds a directory, you do a recursive remove of this directory. No surprise that your files are gone.

You can't use rm -r when you want to spare certain files from deletion. This means that you also can't remove a directory, which somewhere below in its subtree has a file you want to keep.

I would run two find commands: The first removes all the files, ignoring directories, and second one removes all directories, which are empty (bottom-up). Assuming that SAMN03272854 is indeed a file (as you told us in your question), this would be:

find . -type f \( ! \( -name SAMN03272854 -o -name SAMN03272855  \) \) -exec rm {}

find . -depth -type d -exec rmdir {} 2>/dev/null

The error redirection in the latter command suppresses messages from rmdir for directories which still contain files you want to keep. Of course other messages are also suppressed. I would during debugging run the command without error redirection, to see whether it is basically correct.

Things would get more complicated, if you have files and directories to keep, because to keep a directory likely implies to keep all the files below it. In this case, you can use the -prune option of find, which excludes directories including their subdirectories from being processed. See the find man page, which gives examples for this.

  • Related