Separating characters of a string, bash shell

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.

Answers


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...


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')

From http://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

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


Use a while loop on your input.

#!/bin/bash
INPUT="$1"
while read -n 1 CHAR
    mkdir "$CHAR"
    cd "$CHAR"
done <<<"$INPUT"

Need Your Help

AngularJs Table Sorting when Data is nested

javascript angularjs sorting

How can I approach table sorting in angularjs, when my data is nested and not all columns are first level citizens of the objects.

Parse XML file in java parsing new line problem

java xml

XMLInputFactory factory = XMLInputFactory.newInstance();