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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Merging fields within a file

Status
Not open for further replies.

jasperx

Technical User
Jan 9, 2002
26
US
I have a well structured comma separated file which has approximately 20 fields... some may have a few less. I would like to "merge" all of the fields $15 through NF into a single field. What I have written is working on my header line but blowing up on the subsequent lines... most of which start,,, with some empty fields. Here is my code so far:
#!/bin/awk -f

BEGIN {
FS=","
OFS=","
RS="\n"
ORS="\n"
}

{ #Loop through printing first 14 fields separated by commas
for (i=1; i<=NF; i++){
if (i<15){
printf(&quot;%s,&quot;, $i)
}
else{
printf(&quot;%s&quot;, $i)
}
}
}
 
something like that:

BEGIN {
FS=OFS=&quot;,&quot;
FSpivot=15
}
{
for(i=1; i<=NF; i++)
printf(&quot;%s&quot;, (i < FSpivot) ? i OFS : i);
print &quot;&quot;;
}

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Maybe something like but I am not getting it to work...FSpivot probably needs to be $FSPivot? Still no joy... my text shows the contditional statement a little different but that didn't work either.
All are getting this message:
awk: syntax error at source line 2
context is
>>> ? <<<

Here is a cut and paste of that code again:
Code:
BEGIN { 
  FS=OFS=&quot;,&quot; 
  FSpivot=15 
}
{
  for(i=1; i<=NF; i++) 
    printf(&quot;%s&quot;, (i < FSpivot) ? i OFS : i); 
  print &quot;&quot;; 
}
 
Try something like this:
Code:
BEGIN{FS=OFS=&quot;,&quot;;FSPivot=15}
{for(i=1;i<=NF;++i)
  if(i<FSPivot) printf(&quot;%s,&quot;,$i); else printf(&quot;%s&quot;,$i)
 printf &quot;\n&quot;
}


Hope This Help
PH.
 
works fine with Solaris' 'nawk' and MKS's awk.

If on Solaris try with 'nawk'.

If not on Solaris, PHV's alternative should be sufficient.

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top