1

I've used mkdir to create a parent folder with an additional 10 child folders using mkdir -p parent\child{1..10}. I now need to create a txt file in each of these 10 child folders as (name of parent folder).txt

I cannot use touch command as each text document also needs to have a line of text in.

My original idea was to create a loop which would make each child folder and txt file with the specified line of text individually 10 times. I figured this would be inefficient.

I can create all 10 child folders and the parent folder with a single command. How would I go about creating the text files in an efficient manner with the line of text? Or was my original idea the best way to go about it?

2
  • each text document also needs to have a line of text - what text line? is it just the same text for all files? Nov 26, 2017 at 21:56
  • Would just need the name of the child folder it's stored in inside the text file. So "This file is stored in $foldername"
    – DMck
    Nov 26, 2017 at 22:07

1 Answer 1

2

The one of the approaches may look as:

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

Viewing results:

$ 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
1
  • This is perfect, thank you very much. I didn't think of using ##*/ to remove the substring from the dir variable.
    – DMck
    Nov 26, 2017 at 23:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .