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:
a/
, c/
and f1.txt
. For c/
, the directory itself and all sub content (files and directories) will be deleted.kept.txt
, the format is one item (file or directory) per line.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With