2016-06-22 42 views
0

多くのサブディレクトリにたくさんのファイルがあります。Bash:再帰的にサブディレクトリを再作成

私はそれらに対していくつかのタスクを実行し、結果を新しいファイルで返しますが、入力とまったく同じサブディレクトリを持つ出力ディレクトリに戻したいと思います。

私はこのすでに試してみてください。

#!/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といくつかのことをしようとしたが、私は成功しませんでした:/

+0

'find -exec'の使用を検討してください。 –

+0

あなたが '../../../dir1'のようなパスを' $ i'の 'dir1'でちょうど作成したいのであれば、それは私の問題です。 – Inian

+0

です。私は$ ouput/dir1/ –

答えて

1

最も簡単

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を使用して古いフォルダパスを新しいフォルダに置き換えると、ループを回避することもできます。

+0

'for $(コマンド置換)'は使わないでください。[Bash Pitfall#1](http://mywiki.wooledge.org/BashPitfalls#for_i_in_.24.28ls_.2A.mp3.29)を参照してください。 – andlrc

関連する問題