使用 find 查找目录并将其移动到其他路径

使用 find 查找目录并将其移动到其他路径

我有数百个目录中的数十万个文件。

示例目录结构如下

./main/foo1/bar/*
./main/foo2/bar/*
./main/foo3/bar/*
./main/foo1/ran/*
./main/foo2/ran/*

对于具有“bar”目录的文件夹,我想将内容移动到以下结构。

./secondary/bar/foo1/*
./secondary/bar/foo2/*
./secondary/bar/foo3/*

可以使用 find 和 mv 来完成吗?

答案1

一些小脚本可以实现这一点:

# Set the variables
main="./main"
secondary="./secondary"
foo_depth=3
bar_depth=4
bar_name="bar"

# let * match hidden files
shopt -s dotglob

# Loop through find (which is declared after done)
while IFS= read -r dir; do

    # Read names of foo dir
    foo=$(printf '%s' "$dir" | cut -d'/' -f $foo_depth)

    # mkdir target and mv dir there
    target="${secondary}/${bar_name}/${foo}"
    mkdir -p "$target"
    mv "$dir"/* "$target"

    # as you mv the content of bar dir only,
    # you may want to remove the full path to that folder
    # rmdir -p will do that without deleting anything that is not empty,
    # we can ignore the "failed to remove" messages.
    [ $? = 0 ] && rmdir -p "${dir}"

done < <(find "$main" -type d -name "$bar_name")

# Turn off dotglob
shopt -u dotglob

相关内容