我有一个 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/