【问题标题】:Bash: Recreate recursively sub-directoriesBash:创建递归子目录
【发布时间】:2016-10-23 22:43:21
【问题描述】:

我在很多子目录中有很多文件。

我想对它们执行一些任务并将结果返回到一个新文件中,但在一个与输入具有完全相同的子目录的输出目录中。

我已经尝试过了:

#!/bin/bash

########################################################

# $1 = "../benchmarks/k"
# $2 = Output Folder;
# $3 = Path to access the solver

InputFolder=$1;
OutputFolder=$2;

Solver=$3

mkdir -p $2;

########################################
#
# Send the command on the cluster 
# to run the solver on the instancee.
#
########################################
solveInstance() {

    instance=$1;

#   $3 $instance > $2/$i.out 
}

########################################
#
# Loop on benchmarks folders recursively
#
########################################
loop_folder_recurse() {

    for i in "$1"/*;
    do
        if [ -d "$i" ]; then

            echo "dir: $i"

            mkdir -p "$2/$i";

            loop_folder_recurse "$i"

        elif  [ -f "$i" ]; then

            solveInstance "$i"

        fi

    done
}

########################################
#
# Main of the Bash script.
#
########################################

echo "Dir: $1";

loop_folder_recurse $1

########################################################

问题是我的线路mkdir -p "$2/$i";$2 是我们一开始创建的目录的名称,所以没有问题。但在$i 中,它可以是绝对路径,在这种情况下,它希望创建所有子目录以到达文件:不可能。或者它可以包含.. 并出现同样的问题......

我不知道如何修复这个错误:/ 我用sed 尝试了一些东西,但我没有成功:/

【问题讨论】:

  • 您可以考虑使用find -exec
  • 你的意思是如果你有一个像../../../dir1 这样的路径,你想用dir1 创建$i
  • 没错,这是我的问题。我想创建 $ouput/dir1/
  • @ValentinMontmirail:如果是这种情况,您只需使用basename(dir1),它将单独返回dir1,其中dir1 可能包含上述相对路径。

标签: bash recursion directory


【解决方案1】:

最简单的方法是使用find

for i in `find $1 -type d` # Finds all the subfolders and loop.
do
    mkdir ${i/$1/$2} # Replaces the root with the new root and creates the dir.
done

通过这种方式,您可以在 $2 中重新创建 $1 的文件夹结构。如果您使用 sed 将旧文件夹路径替换为新文件夹路径,您甚至可以避免循环。

【讨论】:

猜你喜欢
  • 2011-10-10
  • 2010-12-16
  • 2017-09-12
  • 1970-01-01
  • 2012-06-12
  • 2016-08-13
  • 2011-07-28
  • 1970-01-01
相关资源
最近更新 更多