Quantcast
Channel: UNIX and Linux Forums
Viewing all articles
Browse latest Browse all 16232

Make all records with the same number of fields (awk)

$
0
0
Hi,

input:
Code:

AA|BB|CC
DD|EE
FF

what I am trying to get:
Code:

AA|BB|CC
DD|EE|
FF||

I tried to create first an UDF for printing repeats, but I think I have an issue with my END section or my array:
Code:

function repeat(str, n, rep, i)
{
  for(i=1 ;i<n;i++)
      rep=rep str
      return rep
}

BEGIN{FS=OFS="|"}
{
  a[NR]=$0
  if(NF>max){
      max=NF}
}

END{
  for(i in a){
      if(NF<max){
        x=(max-NF)
        print a[i] repeat("|",x)}
      else{
        print a[i]}
  }
}

With this code it adds the same number of "|" no matter the number of fields the record contains:
Code:

AA|BB|CC|
DD|EE|
FF|

NOTE: I am using gawk (just in case I would have missed a built-in function for printing repeats)

Viewing all articles
Browse latest Browse all 16232

Trending Articles