2

I want to take a word as input and creating consecutive directories using the letters of this word in unix shell. I tried sed, awk and fold commands but did not obtaiın any useful result. Any advice?

For example: If input is hello, it should create h/e/l/l/o directories as one inside another. In other words, h will be the top directory and o will be the deepest subdirectory.

Cœur
  • 37,241
  • 25
  • 195
  • 267
scooter
  • 23
  • 2

2 Answers2

2

This should do the trick in any Bourne compatible shell:

$ mkdir -p $(echo foobar | sed 's:\(.\):\1/:g')
$ find f
f
f/o
f/o/o
f/o/o/b
f/o/o/b/a
f/o/o/b/a/r

Note that \1 is a backreference to the text matched by the first pair of \(...\). Note also that the expansion result is mkdir -p f/o/o/b/a/r/ -- but mkdir ignores the trailing slash to our advantage.

Jens
  • 69,818
  • 15
  • 125
  • 179
1
mkdir -p $(echo $1 | sed 's/[0-9a-zA-Z]/\0\//g')

EDIT: I suppose some explanation is in order:

  1. mkdir -p to make a directory tree
  2. the directory in question is made from the input, with a transformation
  3. the transformation is that any letter or number is turned into itself, followed by a / character
zebediah49
  • 7,467
  • 1
  • 33
  • 50
  • If you want to deal with any characters, `mkdir -p "$(echo "$1" | sed 's/./\0\//g')"`. Additional quotes to deal with space characters, and an 'any character' match. – zebediah49 Apr 26 '13 at 19:49
  • when i tried this, i got all the directories which are equal to 0. – scooter Apr 26 '13 at 19:53
  • This doesn't work. What's `\0` supposed to be? It's a literal 0 on FreeBSD and the POSIX Standard renders it undefined behavior. – Jens Apr 26 '13 at 20:06