Shell script: How to delete all files in a directory except those listed in a file?

I have a directory ( ~/temp/ ) that contains many files and subdirectories, and in some directories they may contain other files and subdirectories. In addition, in the directory ( ~/temp/ ) it contains a special txt file called kept.txt , it lists some direct files and subdirectories that are contained in ~/temp/ , now I want to delete all other files and directories in ~/temp/ , which are not specified in the file kept.txt , how to do this using the shell command, the easier.

eg.

I like the catalog as shown below:

 $ tree temp/ -F temp/ β”œβ”€β”€ a/ β”œβ”€β”€ b/ β”œβ”€β”€ c/ β”‚  β”œβ”€β”€ f2.txt β”‚  └── z/ β”œβ”€β”€ f1.txt └── kept.txt 

Content kept.txt :

 $ more kept.txt b kept.txt 

In this case:

  • I want to remove a/ , c/ and f1.txt . For c/ the directory itself and all sub content (files and directories) will be deleted.
  • In kept.txt format is one item (file or directory) per line.
+6
source share
2 answers

Using extglob , you can do this:

 cd temp shopt -s extglob rm -rf !($(printf "%s|" $(<kept.txt))) 

printf "%s|" $(<kept.txt) printf "%s|" $(<kept.txt) will provide output as b|kept.txt| , and !(...) is an extended glob pattern to deny matching.

+3
source

Move everything to a temporary folder. Move the files / directories listed in .txt. Then finally delete the temporary folder.

+1
source

All Articles