mkdir リスト内のコンテンツを含むテキスト ファイルを作成する

mkdir リスト内のコンテンツを含むテキスト ファイルを作成する

私はmkdirを使って親フォルダを作成し、さらに10個の子フォルダを作成しました。mkdir -p 親\子{1..10}. これらの 10 個の子フォルダのそれぞれに (親フォルダの名前).txt という txt ファイルを作成する必要があります。

各テキスト ドキュメントにも 1 行のテキストが必要なので、touch コマンドは使用できません。

私の当初のアイデアは、指定されたテキスト行を含む各子フォルダーと txt ファイルを個別に 10 回作成するループを作成することでした。これは非効率的だと考えました。

1 つのコマンドで、10 個の子フォルダーと親フォルダーをすべて作成できます。テキスト ラインを使用して、テキスト ファイルを効率的に作成するにはどうすればよいでしょうか。それとも、私の当初のアイデアが最善の方法だったのでしょうか。

答え1

アプローチの 1 つは次のようになります。

mkdir -p parent/child{1..10}
for d in parent/child{1..10}; do echo "This file is stored in ${d##*/}" > "$d/parent.txt"; done

結果の表示:

$ head parent/child*/parent.txt
==> parent/child10/parent.txt <==
This file is stored in child10

==> parent/child1/parent.txt <==
This file is stored in child1

==> parent/child2/parent.txt <==
This file is stored in child2

==> parent/child3/parent.txt <==
This file is stored in child3

==> parent/child4/parent.txt <==
This file is stored in child4

==> parent/child5/parent.txt <==
This file is stored in child5

==> parent/child6/parent.txt <==
This file is stored in child6

==> parent/child7/parent.txt <==
This file is stored in child7

==> parent/child8/parent.txt <==
This file is stored in child8

==> parent/child9/parent.txt <==
This file is stored in child9

関連情報