Home > front end >  Create folder tree from text file, folder names can contain spaces
Create folder tree from text file, folder names can contain spaces

Time:05-14

I have a text file and I need to create the folder tree with a for loop in a script.

Here's the text file I need to use.

Animals.txt

Animals
Animals/Cats
Animals/Cats/Bengal
Animals/Cats/Sphynx
Animals/Dogs
Animals/Dogs/Poodle
Animals/Dogs/Golden Retriever

Here's what I wrote in my script.

for i in $(cat Animals.txt)
do
mkdir "$i"
done

My problem is that when the loop goes into the last line, it creates two folders; One is Animals/Dogs/Golden and the other is Retriever. What should I write in my script to let it know "Golden Retriever " should be a single folder?

CodePudding user response:

After browsing for a bit, I found this. I added this to the start of my script and now the space is not considered.

IFS=$'\n'

CodePudding user response:

Couple small changes to OP's current code:

while read -r newdir
do
    mkdir -p "${newdir}"
done < Animals.txt

This generates:

$ find Animals -type d
Animals
Animals/Cats
Animals/Cats/Bengal
Animals/Cats/Sphynx
Animals/Dogs
Animals/Dogs/Golden Retriever
Animals/Dogs/Poodle

CodePudding user response:

You can use bash mapfile to read your file into an array:

mapfile -t dirs < Animals.txt
mkdir -p "${dirs[@]}"
  • Related