Parth Gandhi
Parth Gandhi

Reputation: 351

Create multiple folders and subfolders

I need to create multiple directories and then subdirectories under each directories. I am able to write the script for creating directories but how do i achieve this for sub directories. Folder Structure:

-User1
   -FolderA
       -FolderA1
   -FolderB
   -FolderC
       -FolderC1
       -FolderC2
    -FolderD
-User2
   -FolderA
       -FolderA1
   -FolderB
   -FolderC
       -FolderC1
       -FolderC2
    -FolderD
-User3
   -FolderA
       -FolderA1
   -FolderB
   -FolderC
       -FolderC1
       -FolderC2
    -FolderD

I am able to achieve this in windows throug CSV file using powershell. Not sure how to get it in linux.

Upvotes: 2

Views: 526

Answers (2)

ceving
ceving

Reputation: 23824

Bash is not very well suited to work with structured data. It is often better to use a different tool like Perl. The following code assumes that you indent the directories only by one space. This simplifies the calculation. If you want to pass your directories from stdin replace <DATA> with <>.

#! /usr/bin/perl
use strict;
use warnings;

my @p = ();
while (<DATA>) {
  s/\n\r?//;
  if (/^(\s*)(.+)$/) {
    my $l = length $1;
    @p = (@p)[0 .. $l];
    $p[$l] = $2;
    my $d = (join '/', @p);
    `mkdir $d`;
  }
}

__DATA__
User1
 FolderA
  FolderA1
 FolderB
 FolderC
  FolderC1
  FolderC2
 FolderD
User2
 FolderA
  FolderA1
 FolderB
 FolderC
  FolderC1
  FolderC2
 FolderD
User3
 FolderA
  FolderA1
 FolderB
 FolderC
  FolderC1
  FolderC2
 FolderD

Upvotes: 0

smaftoul
smaftoul

Reputation: 2683

You can do it like this:

$ mkdir -p foo/{bar,baz}
$ find foo/
foo/
foo/bar
foo/baz

Or:

$ mkdir -p foo/bar foo/baz
$ find foo/
foo/
foo/bar
foo/baz

Upvotes: 2

Related Questions