bash 脚本 - 扁平化目录结构

bash 脚本 - 扁平化目录结构

我正在寻找一个 shell 脚本,它可以展平给定的目录结构,但前提是该目录中只有 1 个子文件夹。例如:该脚本将展平此文件夹:

/folder
    /subfolder
        file1
        file2

进入:

/folder
    file1
    file2

但会跳过(什么也不做)这个文件夹

/folder
    /subfolder1
    /subfolder2 

预先非常感谢您。

史蒂夫

答案1

一个有点幼稚的方法:

#!/bin/sh

for dir do

    # get list of directories under the directory $dir
    set -- "$dir"/*/

    # if there are more than one, continue with the next directory
    # also continue if we didn't match anything useful
    if [ "$#" -gt 1 ] || [ ! -d "$1" ]; then
        continue
    fi

    # the pathname of the subdirectory is now in $1

    # move everything from beneath the subdirectory to $dir
    # (this will skip hidden files)
    mv "$1"/* "$dir"

    # remove the subdirectory
    # (this will fail if there were hidden files)
    rmdir "$1"

done

使用bash

#!/bin/bash

for dir do

    # get list of directories under the directory $dir
    subdirs=( "$dir"/*/ )

    # if there are more than one, continue with the next directory
    # also continue if we didn't match anything useful
    if [ "${#subdirs[@]}" -gt 1 ] || [ ! -d "${subdirs[0]}" ]; then
        continue
    fi

    # the pathname of the subdirectory is now in ${subdirs[0]}

    # move everything from beneath the subdirectory to $dir
    # (this will skip hidden files)
    mv "{subdirs[0]}"/* "$dir"

    # remove the subdirectory
    # (this will fail if there were hidden files)
    rmdir "${subdirs[0]}"

done

两个脚本都将运行为

$ ./script.sh dir1 dir2 dir3

或者

$ ./script.sh */

在当前目录中的所有目录中运行它。

除了代码中的警告之外,这也无法重新链接符号链接。为此,您必须遍历文件系统中所有可能的位置,查找指向下子目录的链接/folder并重新创建它们,以便它们指向正确的新位置。我不会在这里写那么远的代码。

此外,将内容移出子目录时不会进行检查,以确保 下不存在同名条目/folder

相关内容