Reputation: 169
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???
Upvotes: 1
Views: 121
Reputation: 11786
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
.
Upvotes: 3
Reputation: 6421
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.
Upvotes: 0