假设我有一个名为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
又名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[@]}")
的输出
如果您认为输出正确,请在echo
之前删除rm
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
:嘘...最少打印]