简体   繁体   中英

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

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.

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 '%s\n' "${files[@]}"))

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

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

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

cd yourpath/dir/

for f in *; do
    if ! grep -Fxq "$f" /path/list.txt; then
        rm -r "$f"
    else
        printf "Exists -- %s \n" ${f}
    fi
done

In case you are wondering (as I did) what -Fxq means in plain English:

F : Affects how PATTERN is interpreted (fixed string instead of a regex)

x : Match whole line

q : Shhhhh... minimal printing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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