4

I have this output (from a previous command):

aaa         something
bbb         someother
ccc         blabla

For each line, I would like to create a file whose name is the first token, and whose content is the second token (for example for the first line I would like a file named 'aaa' that contains the text 'something')

How should I do this?

3 Answers 3

5

A simple awk script solution. The second field is written to a file named from the first field.

awk '{ print $2 > $1 }' your-file
6
  • It doesn't work.. Commented Dec 19, 2013 at 11:41
  • @RubanSavvy, that certainly works for me: pastebin.com/XRhcSLPa Commented Dec 19, 2013 at 11:48
  • awk: (FILENAME=ru.txt FNR=1) fatal: expression for '>' redirection has null string value I had this error. Commented Dec 19, 2013 at 11:50
  • I tried the same file content but with diff file name.. Commented Dec 19, 2013 at 11:52
  • I'm using CentOS 6 gwak. Commented Dec 19, 2013 at 11:59
2

@suspectus's answer is right on. For more complicated cases where you might have something like this:

aaa         something, something more and a bit extra
bbb         someother someother more and a few more chars
ccc         blabla blah blah boloum bloum bleh

And would like the name to be the first field and the contents to be the rest of the line, try this:

awk '{for(i=2; i<=NF; i++){ printf $i" " >> $1 };print "" >> $1;}' file

Or, in Perl:

perl -ane 'open($f,">",shift(@F));print $f "@F\n"' file
2
your_command | while read name text; do
        echo "$test" > $name
    done

Note that the IFS envoronment variable is going to influence the way this is parsed (word splitting) and that you have to be extra careful about not having "special" characters in the file names (and the text).

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.