![](/img/trans.png)
[英]Shell script to delete files and folders that don't exist in another folder
[英]Delete files and folders in a directory which don't match a text list
假设我有一个名为dir
的目录。 在那个目录中,我有这些文件夹和文件:
folder1
folder2
folder3
file1.mp4
file2.mkv
file3.mp4
我有一个名为list.txt
的文本文件,其中包含以下几行:
folder1
file3
我想从目录中删除列表文件中不可用的所有内容。 这意味着这些将不会被删除:
folder1
file3.mp4
这些将被删除:
folder2
folder3
file1.mp4
file2.mkv
我努力了:
for f in *; do
if ! grep -qxFe "$f" list.txt; then
....
但这并不能提供我想要的结果。 请注意,并非所有文件名都在列表中具有扩展名。
另一种选择是避免循环,只需将文件保存在数组中。 使用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[@]}"
签出grep -Fvwf list.txt <(printf '%s\n' "${files[@]}")
的 output
如果您认为 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
如果您想知道(就像我一样) -Fxq
在简单的英语中是什么意思:
F
:影响 PATTERN 的解释方式(固定字符串而不是正则表达式)
x
:匹配整行
q
: Shhhhh...最小打印
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.