[英]Delete files and folders in a directory which don't match a text list
Let's say I have a directory named dir
.假设我有一个名为
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:我有一个名为
list.txt
的文本文件,其中包含以下几行:
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.使用
mapfile
aka readarray
这是一个 bash4+ 功能。
#!/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[@]}")
签出
grep -Fvwf list.txt <(printf '%s\n' "${files[@]}")
的 output
Remove the echo
before the rm
if you think the output is correct如果您认为 output 正确,请删除
rm
之前的echo
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:如果您想知道(就像我一样)
-Fxq
在简单的英语中是什么意思:
F
: Affects how PATTERN is interpreted (fixed string instead of a regex) F
:影响 PATTERN 的解释方式(固定字符串而不是正则表达式)
x
: Match whole line x
:匹配整行
q
: Shhhhh... minimal printing q
: Shhhhh...最小打印
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.