【问题标题】:delete directories not in the file containing directory names list删除不在包含目录名称列表的文件中的目录
【发布时间】:2015-06-16 03:20:26
【问题描述】:

我有一个文件,其中包含我要保留的目录名称列表。说 file1 其内容是目录的名称,如

  • 目录 1
  • dir2
  • 目录3

另一方面,我的目录(实际目录)有像

这样的目录
  • 目录1
  • dir2
  • 目录3
  • dir4
  • 目录

我要做的是从我的目录中删除 dir4, dirs 和其他在 file1 上不存在其名称的目录。 file1 每行都有一个目录名。 dir4 和 dirs 下可能有需要递归删除的子目录或文件。

我可以使用 xargs 删除我的目录中列表中的文件

xargs -a file1 rm -r

但我不想删除,而是想保留它们并删除不在 file1 上的其他文件。可以的

xargs -a file1 mv -t /home/user1/store/

并删除我目录中的剩余目录,但如果有更好的方法,我正在徘徊?

谢谢。

【问题讨论】:

  • for x in */; do grep -q "$x" list_file || rm -rf "$x"; done ?
  • @anishsane 这会删除所有目录,尽管目录名称不在列表中。
  • 我的错...我忘记了结尾的/。试试这个:for x in */; do grep -q "${x%/}" list_file || rm -rf "$x"; done

标签: bash shell xargs


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

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-04
      相关资源
      最近更新 更多