Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AWK. Read file, create file using field $2 as the name. 3

Status
Not open for further replies.

stevenawk

Programmer
Nov 12, 2008
9
DE
Hi,

I'm on a Java project and we've found ourselves needing the beautiful language of AWK!

Problem:

I am reading through a file, line-by-line which looks like this:
---------------------------
[dataA1] {dataA2}
[dataB1] {dataB2}
[dataC1] (dataC2}
garbageG1
garbageG2
[dataD1] {dataD2}
---------------------------

If the first character of field 1 is a "[", then make a file which must be named using the value in field 2. This new file must contain the the line from the file being currently looked at.
Else, the line is garbage, so: it needs to be added to the previous newly made file. When adding this line of garbage it must be prefixed with field 1 and field 2 that the newly made file was populated with.

So the results would be:

A file called "dataA2" which has 1 line which is:
"[dataA1] {dataA2}".
A file called "dataB2" which has 1 line which is:
"[dataB1] {dataB2}".
A file called "dataC2" which has 3 lines which are:
"[dataC1] {dataC2}
[dataC1] {dataC2} garbageG1
[dataC1] {dataC2} garbageG2".
A file called "dataD2" which has 1 line which is:
"[dataD1] {dataD2}".


wow !

Any help would be great. I've got bits and pieces myself but i cant put it together.

Steve
 
That was quick!

Would you mind breaking this down into an explanation please?

Other solutions are also still welcome :)

Steve
 
Hi

Code:
awk '
/^\[.*\]/ {         [gray]# if current line starts with "[" + any chars + "]"[/gray]
  [b]if[/b] (f) [b]close[/b](f)   [gray]# if we have file name ( so an open file too ), close it[/gray]
  f=l=$0            [gray]# put the current line both in file name and last line vars[/gray]
  sub(/.*{/,[i]""[/i],f)   [gray]# remove any chars + "{" from file name[/gray]
  sub(/}/,[i]""[/i],f)     [gray]# remove "}" + any chars from file name[/gray]
  [b]print[/b]>f           [gray]# write the current line to the new file[/gray]
  [b]next[/b]              [gray]# jump to next input line ( skip the following code )[/gray]
}
{                   [gray]# always ( when execution reaches this line ) do[/gray]
  [b]print[/b] l,$0>>f     [gray]# append the last line and the current line to the file[/gray]
}
' /input/file

Feherke.
 
Thanks a lot feherke,

we had to adjust a bit as our requirements changed.

thanks,

S.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top