Question

I'm just having the darnedest time with this. Here is my nawk statement:

nawk -F"\t" '{print substr($1,0,4)","substr($1,5,4)","substr($1,9,4)","$2","$3","$4","$5","$6}' filename

In a nutshell, this is a tab delimited file. I want to split the first column (12 chars) into 3 columns and I do that with the substring function. Then, I'd like to print the rest of the data without the first column. It's the appending part that I'm having an issue with.

In its current iteration, the lines that don't have 6 columns will have hanging commas and the ones that have greater than 6 columns don't get printed.

Any thoughts?

Was it helpful?

Solution

Untested, but try this:

nawk -F"\t" -v OFS=, '
    {$1 = substr($1,0,4) OFS substr($1,5,4) OFS substr($1,9,4)}
    {print}
' filename

Update for comment -- I assume you want every field in quotes:

nawk -F"\t" -v OFS=, -v q="'" '
  {
    $1 = q substr($1,0,4) q OFS q substr($1,5,4) q OFS q substr($1,9,4) q
    for (i=2; i<=NF; i++) 
      $i = q $i q
    print
  }
' filename

I pass a single quote into nawk as a variable because you cannot embed a single quote into a single quoted string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top