How do I write every line to a separate file using awk?

Viewed 143

I would like to write every line of a txt-file to a separate file and use the first column as the name of the new file. The new file should then contain everything else in the line, but column 1.

So when I have:

example_1 a b c d
example_2 e f g h
example_3 j k l m

I want 3 separated files that are named example_1.mop, example_2.mop and example_3.mop and contain everything after the first column. So example_1.mop should contain a b c d and so on.

I almost found a way with

awk '{printf "%s\n", $2>$1".mop"}' file

but this only puts the second column in the new file. How can I tell awk to use everything else but the first column?

Thanks a lot for your help!

2 Answers

With your shown samples, please try following. Written and tested in GNU awk, should work in any awk.

awk '
{
  first=$1
  $1=""
  sub(/^ +/,"")
  outputFile=first".mop"
  print >> (outputFile)
  close(outputFile)
}
' Input_file

Explanation: Adding detailed explanation for above.

awk '                    ##Starting awk program from here.
{
  first=$1               ##Creating first which has 1st field in it.
  $1=""                  ##Nullify 1st field here.
  sub(/^ +/,"")          ##Substituting initial space with NULL here.
  outputFile=first".mop"    ##Creating outputFile which has output file name in it.
  print >> (outputFile)  ##Printing current line into output file.
  close(outputFile)      ##Closing output file in backend.
}
' Input_file             ##Mentioning Input_file name here.
awk '{out=$1".mop"; sub(/[^[:space:]]+[[:space:]]*/,""); print > out; close(out)}' file
Related