1

I'm trying to write a script that takes one string argument, divides the string into characters and uses the characters to create directory.

Ex: "./addUser asd" should create a directory named "a" inside the directory that the script is located, it also has to create a directory named "s" as a child directory of "a". Similarly, a directory named "d" has to be created inside the directory "s".

I'm stuck, can you please help?

Thanks in advance.

user2117336
  • 69
  • 1
  • 3
  • possible duplicate of [manupulating a string to create directories in unix](http://stackoverflow.com/questions/16244046/manupulating-a-string-to-create-directories-in-unix) – Kevin May 02 '13 at 20:29

5 Answers5

1

The easiest way that comes to mind is use a regex to insert / between each pair or characters with mkdir -p, like:

mkdir -p $(echo abc | perl -pi -e 's!.(?=.)!$&/!g')

or with sed:

mkdir -p $(echo abc | sed -e 's!.!&/!g')
FatalError
  • 52,695
  • 14
  • 99
  • 116
0

From https://stackoverflow.com/a/7579016/2313067, you can use something like

x=$1
i=0
while [ $i -lt ${#x} ]; do mkdir ${x:$i:1}; cd ${x:$i:1};  i=$((i+1));done
Community
  • 1
  • 1
user2313067
  • 593
  • 1
  • 3
  • 8
0

One possible solution with mkdir -p:

echo asd | sed 's:.:&/:g' | xargs -n1 -I % mkdir -p "%"

or as usual eliminating the useless echo :) and the script format

#/bin/bash
<<< "$1" sed 's:.:&/:g' | xargs -n1 -I % mkdir -p "%"

this can be used as

< filename sed 's:.:&/:g' | xargs -n1 -I % mkdir -p "%"

the names are in the file filename

or

mkdir -p $(echo asd | sed 's:.:&/:g')

or

mkdir -p $(sed 's:.:&/:g' <<< "asd")

as usually, spaces and some special chars could make troubles...

clt60
  • 62,119
  • 17
  • 107
  • 194
  • Thank you,this works fine. But I also have another similar problem. Now I have to create a text file in the directory, say, "d". The child directory. How can I do that? – user2117336 May 02 '13 at 21:04
0

I answered something similar to this a few days ago:

manupulating a string to create directories in unix

It boils down to

mkdir -p $(echo $1 | sed 's/[0-9a-zA-Z]/\0\//g')

or something similar

Community
  • 1
  • 1
zebediah49
  • 7,467
  • 1
  • 33
  • 50
0

Use a while loop on your input.

#!/bin/bash
INPUT="$1"
while read -n 1 CHAR
    mkdir "$CHAR"
    cd "$CHAR"
done <<<"$INPUT"
Spencer Rathbun
  • 14,510
  • 6
  • 54
  • 73