shell 删除不在包含目录名列表的文件中的目录

nwo49xxi  于 2022-12-13  发布在  Shell
关注(0)|答案(3)|浏览(183)

我有一个文件,其中包含我想保留的目录名列表。比如说file 1,它的内容是目录名,如

  • 目录1
  • 目录2
  • 目录3

另一方面,我的目录(实际目录)具有如下目录

  • 目录1
  • 目录2
  • 目录3
  • dir4
  • 迪尔斯

我想做的是从我的目录中删除dir 4、dirs和其他名称在file 1中不存在的目录。file 1每行都有一个目录名。dir 4dirs下可能有子目录或文件,需要递归删除。
我可以使用xargs删除My目录中列表中的文件
xargs -a文件1 rm -r
但我不想删除,而是想保留它们,并删除不在文件1上的其他文件。可以吗
xargs -文件1 mv -t /主目录/用户1/存储/
并删除我的目录中剩下的目录,但我徘徊,如果有更好的方法?

  • 谢谢-谢谢
7kqas0il

7kqas0il1#

find . -maxdepth 1 -type d -path "./*" -exec sh -c \
    'for f; do f=${f#./}; grep -qw "$f" file1 || rm -rf "$f"; done' sh {} +
elcex8rz

elcex8rz2#

Anish有一个很好的简单答案。如果你想要一些详细的东西来帮助你在未来进行数据操作或类似的事情,下面是一个详细的版本:

#!/bin/bash

# send this function the directory name
# it compares that name with all entries in
# file1. If entry is found, 0 is returned
# That means...do not delete directory
#
# Otherwise, 1 is returned
# That means...delete the directory
isSafe()
{
    # accept the directory name parameter
    DIR=$1
    echo "Received $DIR"

    # assume that directory will not be found in file list
    IS_SAFE=1 # false

    # read file line by line
    while read -r line; do

        echo "Comparing $DIR and $line."
        if [ $DIR = $line ]; then
            IS_SAFE=0 # true
            echo "$DIR is safe"
            break
        fi

    done < file1

    return $IS_SAFE
}

# find all files in current directory
# and loop through them
for i in $(find * -type d); do

    # send each directory name to function and
    # capture the output with $?
    isSafe $i
    SAFETY=$?

    # decide whether to delete directory or not
    if [ $SAFETY -eq 1 ]; then
        echo "$i will be deleted"
        # uncomment below
        # rm -rf $i
    else
        echo "$i will NOT be deleted"
    fi
    echo "-----"

done
idv4meu8

idv4meu83#

您可以使用grep排除目录:

find . -mindepth 1 -maxdepth 1 -type d -printf '%P\n' | grep -f file1 -Fx -v | xargs rm -r

-printf '%P\n'用于从目录名中删除前导'./'
来自man find-printf说明:
%磷 文件的名称与发现其被移除的起始点的名称。
grep参数:
-f文件 从FILE中获取模式,每行一个。
-F  将PATTERNS解释为固定字符串,而不是正则表达式。
-x  只选择与整行完全匹配的匹配项。对于正则表达式模式,这类似于将模式括在括号中,然后用^和$将其括起来。
-v  反转匹配的意义,以选择不匹配的行。

相关问题