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?


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

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

@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
| improve this answer | |
your_command | while read name text; do
        echo "$test" > $name

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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.