ファイルを繰り返し( 'for file in...)、サブディレクトリも含めますか?

ファイルを繰り返し( 'for file in...)、サブディレクトリも含めますか?

私はファイルをたくさん変更するためにsedを使用しています。この質問は、パターンに一致するファイルを繰り返し、元のファイル検索の再帰とファイル生成出力にサブディレクトリを含めたいすべての操作に関連していると思います(つまり、構造をコピーするために作成)。

私が最初に受け取ったファイルは

mkdir -p _seded
for file in *_spec.rb
do
  cat $file
  ... a bunch of seds
  > _seded $file
end

プラスファイルはどのように入手できますか?サブディレクトリファイルマッチパターン?

たとえば、私が持っている場合

spec/ex1
spec/ex2_spec.rb
spec/subs/subex1
spec/subs/subex1_spec.rb
spec/subs/subex2/aaa
spec/subs/subex3/s3_spec.rb
spec/subs/subex4/s4.rb
spec/subs/subex4/bbb

それから私は以下を得るべきです:

_seded/ex2_spec.rb
_seded/subs/subex1_spec.rb
_seded/subs/subex3/s3_spec.rb

注: subex2 および subex4 ディレクトリはいいえ空のため生成されます。

私は試した:

mkdir -p _seded
find . -name '*_spec.rb' | xargs cat |
  sed -e '[/pattern/replace code]' > _seded/$file

ただし、次のエラーが発生します。

$ ./convert_should_to_expect.sh 
./convert_should_to_expect.sh: line 5: _seded/: Is a directory
xargs: cat: terminated by signal 13
now doing its !!!
sed: couldn't edit _seded/: not a regular file
awk: cmd. line:1: fatal: cannot open file `_seded/' for reading (Is a directory)
mv: `_seded/tmp' and `_seded/tmp' are the same file
sed: couldn't edit _seded/: not a regular file
sed: couldn't edit _seded/: not a regular file

ベストアンサー1

次のことができます。

cd spec
find . -type f -name '*_spec.rb' | while read file; do
    mkdir -p ../_seded/"${file%/*}"
    cat "$file" | sed ... > ../_seded/"$file"
done

${file%/*}$file出力ディレクトリの作成に使用できるように、ファイル名部分を切り捨てます。mkdir command

おすすめ記事