manshou
manshou

Reputation: 357

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

I have a directory (~/temp/) that contains many files and sub directories, and in some directories, they may contain other files and sub directories. Also, in the directory (~/temp/), it contains a special txt file with name kept.txt, it list some direct files and sub directories that contained in ~/temp/, now i want to delete all other files and directories under ~/temp/ that are not listed in the kept.txt file, how to do this with a shell command, the simpler the better.

e.g.

The directory likes as below:

$ tree temp/ -F
temp/
 ├── a/
 ├── b/
 ├── c/
 │   ├── f2.txt
 │   └── z/
 ├── f1.txt
 └── kept.txt

The content of kept.txt is:

$ more kept.txt
b
kept.txt

For this case:

  1. i want to delete a/, c/ and f1.txt. For c/, the directory itself and all sub content (files and directories) will be deleted.
  2. In kept.txt, the format is one item (file or directory) per line.

Upvotes: 7

Views: 339

Answers (2)

anubhava
anubhava

Reputation: 784898

Using extglob you can do this:

cd temp
shopt -s extglob

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

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

Upvotes: 5

user5291788
user5291788

Reputation:

Move everything to a temporary folder. Move back the files/directories listed in the .txt. Then, last, remove the temporary folder.

Upvotes: 1

Related Questions