1

I have a excel file which i will convert to csv or txt file with following data:

ALFA ROMEO > 147 > Scheinwerferblenden
ALFA ROMEO > 156 > Scheinwerferblenden
ALFA ROMEO > 156 > Kühlergrill
AUDI > 80 B3 > Heckspoiler
.
.

and so on

I need to create folders and subfolders based on this data with following syntax:

├───ALFA ROMEO
│            ├───147
│            │     └───Scheinwerferblenden
│            └───156
│                  ├───Scheinwerferblenden
│                  └───Kühlergrill        
│
└───AUDI
       └───80 B3
               └───Heckspoiler

I tried to write mkdir -p bash scripts but with no success.

Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227

2 Answers2

1

With the input you have provided I was able to accomplish this with the following command

while read -r dir; do mkdir -p ./"$dir"; done< <(sed 's@ > @/@g' input)

You can replace ./ with the directory path you would like the directory tree to start in, if not the current directory.

This uses sed to convert your input lines from something like:

ALFA ROMEO > 147 > Scheinwerferblenden

to:

ALFA ROMEO/147/Scheinwerferblenden

Then it feeds this output to a while loop that uses mkdir -p to create the directory tree.

$ cat input
ALFA ROMEO > 147 > Scheinwerferblenden
ALFA ROMEO > 156 > Scheinwerferblenden
ALFA ROMEO > 156 > Kühlergrill
AUDI > 80 B3 > Heckspoiler
$ while read -r dir; do mkdir -p ./"$dir"; done< <(sed 's@ > @/@g' input)
$ tree
.
├── ALFA\ ROMEO
│   ├── 147
│   │   └── Scheinwerferblenden
│   └── 156
│       ├── K\303\274hlergrill
│       └── Scheinwerferblenden
├── AUDI
│   └── 80\ B3
│       └── Heckspoiler
└── input

9 directories, 1 file
jesse_b
  • 35,934
  • 12
  • 91
  • 140
  • Thanks, works fine except that it adding ? mark on all lowest level folders – Helmut54321 Mar 08 '18 at 02:33
  • I'm not sure what would cause that, perhaps there is something strange in your input file? If the file was created on windows have you run it through `dos2unix` or something similar? – jesse_b Mar 08 '18 at 02:58
  • i have mac os, input file csv – Helmut54321 Mar 08 '18 at 03:27
  • Mac has a similar issue, you should run the file through mac2unix which comes with the dos2unix package if you brew install it. Or check out this question [What is `^M` and how do I get rid of it?](https://unix.stackexchange.com/questions/32001/what-is-m-and-how-do-i-get-rid-of-it) – jesse_b Mar 08 '18 at 03:34
  • 1
    Thanks Man! This was ^M issue. I edited file via vim and get rid of problem – Helmut54321 Mar 08 '18 at 04:28
0

Try this, based on your input (using bash parameter expansions) :

while IFS=">" read -r c1 c2 c3; do
    c2=${c2% }
    mkdir -p "${c1% }/${c2# }/${c3# }"
done < file-or-input

Output :

$ tree AUDI ALFA\ ROMEO/
AUDI
└── 80 B3
    └── Heckspoiler
ALFA ROMEO/
├── 147
│   └── Scheinwerferblenden
└── 156
    ├── Kühlergrill
    └── Scheinwerferblenden

7 directories, 0 files
Gilles Quénot
  • 31,569
  • 7
  • 64
  • 82