Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

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.
like image 978
manshou Avatar asked Sep 02 '15 08:09

manshou


1 Answers

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.

like image 61
anubhava Avatar answered Oct 16 '22 14:10

anubhava