用于删除文件名不在文本文件中的 Shell 脚本

标签 shell file scripting

我有一个 txt 文件,其中包含文件名列表

示例:

10.jpg
11.jpg
12.jpeg
...

在一个文件夹中,此文件应防止删除过程,其他文件应删除。

所以我想要这个问题的相反逻辑:Shell command/script to delete files whose names are in a text file

如何做到这一点?

最佳答案

使用extglob和 Bash 扩展模式匹配 !(pattern-list) :

!(pattern-list)
Matches anything except one of the given patterns
where a pattern-list is a list of one or more patterns separated by a |.

extglob
If set, the extended pattern matching features described above are enabled.

例如:

$ ls
10.jpg  11.jpg  12.jpeg  13.jpg  14.jpg  15.jpg  16.jpg  a.txt
$ shopt -s extglob
$ shopt | grep extglob
extglob         on
$ cat a.txt
10.jpg
11.jpg
12.jpeg
$ tr '\n' '|' < a.txt
10.jpg|11.jpg|12.jpeg|
$ ls !(`tr '\n' '|' < a.txt`)
13.jpg  14.jpg  15.jpg  16.jpg  a.txt

删除的文件是13.jpg 14.jpg 15.jpg 16.jpg a.txt根据示例。

所以extglob!(pattern-list) ,我们可以根据文件内容获取排除的文件。
此外,如果您想排除以 . 开头的条目,然后您可以打开 dotglob选项 shopt -s dotglob .

关于用于删除文件名不在文本文件中的 Shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44620045/

相关文章:

bash - Sed 在 bash 脚本中不工作

shell - 子shell中对$RANDOM的引用都返回相同的值

java - 如何读取文件并返回字符串及其值

linux - BASH 文件移动

java - 使用java从大文件中读取 block

python - 在命令行应用程序中打印标准输出而不覆盖待处理的用户输入

linux - 文件大于目录的平均大小?

linux - 用于为日志文件中的每个条目添加耗时的命令行脚本或实用程序?

linux - Bash for 远程服务器上的循环

linux - Bash 脚本 : How to display output for the passwords expiry every 2 week