我使用 mkdir 建立了一個父資料夾,其中包含另外 10 個子資料夾mkdir -p 父\子{1..10}。我現在需要在這 10 個子資料夾中的每一個中建立一個 txt 檔案作為(父資料夾的名稱).txt
我無法使用觸控命令,因為每個文字文檔也需要有一行文字。
我最初的想法是創建一個循環,使每個子資料夾和 txt 檔案分別具有指定的文字行 10 次。我認為這效率很低。
我可以使用一個命令創建所有 10 個子資料夾和父資料夾。我將如何使用文字行以有效的方式建立文字檔案?或者我最初的想法是實現它的最佳方式嗎?
答案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