Shell脚本:如何删除目录中除文件中列出的文件以外的所有文件? [英] Shell script: How to delete all files in a directory except ones listed in a file?

查看:59
本文介绍了Shell脚本:如何删除目录中除文件中列出的文件以外的所有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个目录(〜/temp/),其中包含许多文件和子目录,在某些目录中,它们可能包含其他文件和子目录.另外,在目录(〜/temp/)中,它包含一个名为 kept.txt 的特殊txt文件,其中列出了〜/temp/,现在我要删除 kept.txt 文件中未列出的〜/temp/下的所有其他文件和目录,如何使用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.

例如

目录如下:

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

kept.txt 的内容为:

$ more kept.txt
b
kept.txt

在这种情况下:

  1. 我要删除 a/ c/ f1.txt .对于 c/,目录本身和所有子内容(文件和目录)都将被删除.
  2. kept.txt 中,格式为每行一项(文件或目录).
  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.

推荐答案

使用 extglob ,您可以执行以下操作:

Using extglob you can do this:

cd temp
shopt -s extglob

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

printf%s |"$(< kept.txt)将以 b | kept.txt | 的形式提供输出,而!(...)

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

这篇关于Shell脚本:如何删除目录中除文件中列出的文件以外的所有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆