$ cat "

Linux Kata #1: Welcome Messages

"

Time for another kata! The task of the day:

Given the following file (names.txt):



Bernie
Steve
Lisa
Jamie
Adam
Little Johnny

Create the following file structure:


.
|-- names.txt
|-- Adam
| `-- Adam.txt
|-- Steve
| `-- Steve.txt
|-- Little Johnny
| `-- Little Johnny.txt
|-- Lisa
| `-- Lisa.txt
|-- Jamie
| `-- Jamie.txt
`-- Bernie
`-- Bernie.txt

where each of the txt files contains a welcome message on the following format:

Welcome <NAME>, this is your directory!

#i.e.
Welcome Adam, this is your directory!

Tips:
If you don't get it right on the first try, it might come in handy to quickly be able to delete all subdirectories and their content. Here is one way to do that:

find . -mindepth 1 -type d -print0 | xargs -0 rm -rf

This command uses find to list all directories (-type d) one level down from the current directory. This excludes the "." directory. "print0" is used to handle directory names containing whitespace. This needs to be coupled with the -0 option for xargs. xargs is used to execute rm for the output from find. -rf executes a recursive, forced delete of the directories listed by find.

Another useful thing might be to use the -t option for xargs (if your soulution uses xargs) to make it output commands before executing them.

Example solution:
Here is one way to solve the problem above:


cat names.txt | xargs -I {} sh -c 'echo "Hello $1, this is your directory." > "./$1/$1.txt"' -- {}

This command pipes all names from names.txt into xargs, which executes sh for each name in the file. The -I {} option specifies that a given command should be executed for each line from the file, using {} as a placeholder for that line in the command text.

sh -c executes a command string and the -- is used to give sh a parameter to use when executing the command in the command string. $1 in the command string is replaced with the parameter, that is with the value of {}, which is actually the line from the file.

The actual command text executed by sh is nothing fancy, simply create a directory with the same name as the name in the file, and then echo the welcome message into a file with the same name inside the newly created directory.

The reason sh is used in this command is that you can't really execute an xargs command that includes the > operator. If you try to you will simply send the whole command, (find + xargs etc) to the file instead.

Written by Erik Öjebo 2012-11-27 20:45

    Comments