Skip to content
Advertisement

How to create folders and files from paths given in text file

I have a text file named creating.txt. In this file, each line has a path.

  • If line starts with D it means that I have to create directory.
  • If line starts with F, I have to create a file.

For example:

D:/root/F1/Cat1
F:/root/F1/file1.txt
D:/root/F1/Cat1/Cat2

I need to go line by line, first check if first letter is D or F, then ignore the : and the first letter and accordingly create a file or directory based on given path. If first letter in line is not D or F, just ignore the line.

Also if the file already exists I’m not allowed to create another one.

I tried using awk:

path=`awk { print } creating.txt`
touch $path

But the problem is this reads the whole file (not line by line) so there have to be only one line. Also I don’t know how to ignore D: and F:.

Advertisement

Answer

It can be done with two 2 one-liners

I reproduced your input :

$ cat creating.txt
D:/root/F1/Cat1
F:/root/F1/file1.txt
D:/root/F1/Cat1/Cat2

You can use this to create the Directories

$ for path in `grep ^D creating.txt | cut -d: -f2`; do mkdir -p "$path";done

Then, for files

$ for file in `grep ^F creating.txt | cut -d: -f2`; do touch "$file";done

Explanation:
The grep, will select the lines beginning [as I used ^] by D (or F)
The cut, will catch the 2nd field using ‘:’ as delimiter

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement