Delete files and folders in a directory which don’t match a text list

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Delete files and folders in a directory which don’t match a text list on this date .

Let’s say I have a directory named dir. In that directory, I have these folders and files:

folder1
folder2
folder3
file1.mp4
file2.mkv
file3.mp4

I have a text file named list.txt, which has these lines:

folder1
file3

I want to delete everything from dir that is not available in the list file. Meaning these will not be deleted:

folder1
file3.mp4

And these will be deleted:

folder2
folder3
file1.mp4
file2.mkv

I have tried:

for f in *; do
    if ! grep -qxFe "$f" list.txt; then
    ....

but this does not provide the result I want. Note that i not all filename have extension on the list.

Answer

Another option is to avoid the loop, just save the files in an array. using mapfile aka readarray which is a bash4+ feature.

#!/usr/bin/env bash

##: Just in case there are no files the glob will not expand to a literal *
shopt -s nullglob

##: Save the files inside the directory dir (if there are)
files=(dir/*)

##: Save the output of grep in a array named to_delete
mapfile -t to_delete < <(grep -Fvwf list.txt  <(printf '%sn' "${files[@]}"))

echo rm -rf "${to_delete[@]}"

checkout out the output of grep -Fvwf list.txt <(printf '%sn' "${files[@]}")

Remove the echo before the rm if you think the output is correct