awk script for this

HI help,

I could not exactly get an o/p as I would like to.

The i/p file looks like

A 1 4 56
A 1 6 78
B 4 8 10
B 6 7 80

The o/p file should be

X,Y,Z
1 4 56 4
1 4 56 8
1 4 56 10
1 4 56 6
1 4 56 7
1 4 56 80
1 6 78 4
1 6 78 8
1 6 78 10
1 6 78 6
1 6 78 7
1 6 78 80

With the script i am using i get the o/p as

X,Y,Z
1 6 78 4
1 6 78 8
1 6 78 10
1 6 78 6
1 6 78 7
1 6 78 80

The script is

#!/usr/bin/awk -f

BEGIN{
  print("X,Y,Z")
    }

/^A/{
    A1 = $2
    A2 = $3
    A3 = $4 
    }

/^B/{
  B[1] = $2
  B[2] = $3
  B[3] = $4
  
    for (i=1; i<4; i++){
      if (B != "    "){
print(A1,A2,A3,B)
      }
    }
      
}

I am missing a loop FOR 'A'.
Could you please suggest

Thanks,

You need to save the A values into a two-dimensional array as well as the B values. Then have two nested for loops across either index to get at the value combinations and print.

1 Like

Hi Rudi,

Many thanks for your suggestion. I am sorry that I am not that expert in coding, could you please let me know how can I do that.

Thanks,

Try:

#!/usr/bin/awk -f

BEGIN {
  print("X,Y,Z")
}

/^A/ {
    sub($1 FS,x)
    A[++n]=$0
}

/^B/ {
  for (i=2; i<=NF; i++) 
    B[++m]=$i
}

END {
  for(i=1; i<=n; i++)
    for(j=1; j<=m; j++)
      print(A,B[j])
}
1 Like