Search code examples
bashfiledelete-filerm

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?? 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???


Solution

  • 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.