简体   繁体   English

Bash脚本删除目录中的文件,但不同文件中列出的文件除外

[英]Bash Script delete files in directory except those listed in different files

I have two files , let's say 我有两个文件,比方说

root@test:~ $ cat File1.txt

name1
name2
name3


root@test:~$ cat File2.txt

name4
name5
name6

and a Directory that has several filenames 和一个有多个文件名的目录

root@test:~$ ls

name1
name2
name3
name4
name5
name6
name7
name8
name9

How can I Delete the files which aren't on both .txt files?? 如何删除两个.txt文件上都没有的文件? so the final result will be 所以最终的结果将是

root@test:~$ ls
name1
name2
name3
name4
name5
name6

is it possible to write something in bash to do this??? 是否可以用bash写一些东西来做这个???

In the directory you want to delete the files: 在要删除文件的目录中:

for f in *; do
    [ -z $(grep "^${f}$" <(cat /dir/with/File*.txt)) ] && echo rm -f "$f"
done

Will print out a list of files to be deleted. 将打印出要删除的文件列表。 To actually delete them, remove the echo . 要实际删除它们,请删除echo

I would test with something like this: 我会测试这样的东西:

while read -r -d $'\0'; do
    if grep -qs "^$REPLY\$" File1 && grep -qs "^$REPLY\$" File2; then
        # Filename found in both File1 and File2: do nothing
        :
    else
        rm -i "$REPLY"
    fi
done < <(find . -maxdepth 1 -type f -print0)

Unless I'm missing something, this should handle filenames with embedded spaces, newlines, and backslashes correctly. 除非我遗漏了某些东西,否则这应该正确处理带有嵌入空格,换行符和反斜杠的文件名。

You can remove the interactive flag ( -i ) from rm once you're confident that it's doing what you want. 一旦您确信它正在执行您想要的操作,您就可以从rm删除交互式标志( -i )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM