![](/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.