'Create folder tree from text file, folder names can contain spaces
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?
Solution 1:[1]
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'
Solution 2:[2]
Couple small changes to OP's current code:
while read -r newdir # read entire line into variable "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
Solution 3:[3]
You'd do it straight simple with xargs
:
xargs -L 50 -a Animals.txt mkdir -p
xargs
would take up to 50 lines at a time and feed each line as argument to the command mkdir -p
. That would be very efficient and straightforward.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jay Leblanc |
Solution 2 | |
Solution 3 | Léa Gris |