首页 > 解决方案 > 删除目录中的所有文件,列表中提到的文件除外

问题描述

我有一个名为 a00 的目录,其中包含 3000 个扩展名为 .SAC 的文件。我有一个名为 gd.list 的文本文件,其中包含这 3000 个文件中的 88 个的名称。我正在尝试编写一个代码来删除所有 .SAC 文件,除了 gd.list 中提到的文件

如何使用 shell/bash 做到这一点?

标签: linuxbashshell

解决方案


rm命令已被注释掉,以便您可以检查并验证它是否按需要工作。然后取消注释该行。

check directory部分将确保您不会意外地从错误的目录运行脚本并破坏错误的文件。

您可以删除该echo deleting行以静默运行。

#!/bin/bash

cd /home/me/myfolder2tocleanup/

# Exit if the directory isn't found.
if (($?>0)); then
    echo "Can't find work dir... exiting"
    exit
fi

for i in *; do
    if ! grep -qxFe "$i" filelist.txt; then
        echo "Deleting: $i"
        # the next line is commented out.  Test it.  Then uncomment to removed the files
        # rm "$i"
    fi
done

你可以在这里找到答案https://askubuntu.com/questions/830776/remove-file-but-exclude-all-files-in-a-list by LD James


推荐阅读