Python – Unable to separate codes in one file to many files in AWK/Python

awkpython

I need to put different codes in one file to many files.
The file is apparantly shared by AWK's creators at their homepage.
The file is also here for easy use.

My attempt to the problem

I can get the lines where each code locate by

awk '{ print $1 }'

However, I do no know how

  1. to get the exact line numbers so that I can use them
  2. to collect codes between the specific lines so that the first word of each line is ignored
  3. to put these separate codes into new files which are named by the first word at the line

I am sure that the problem can be solved by AWK and with Python too. Perhaps, we need to use them together.

[edit] after the first answer

I get the following error when I try to execute it with awk

$awk awkcode.txt 
awk: syntax error at source line 1
 context is
     >>> awkcode <<< .txt
awk: bailing out at source line 1

Best Answer

Did you try to:

  1. Create a file unbundle.awk with the following content:

$1 != prev { close(prev); prev = $1 } { print substr($0, index($0, " ") + 1) >$1 }

  1. Remove the following lines form the file awkcode.txt:

    # unbundle - unpack a bundle into separate files

$1 != prev { close(prev); prev = $1 } { print substr($0, index($0, " ") + 1) >$1 }

  1. Run the following command:

awk -f unbundle.awk awkcode.txt