Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

up vote 5 down vote accepted

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

awk '{ print $2 > $1 }' your-file
share|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
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).

share|improve this answer

@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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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