0

I have a file with 4 columns. First two columns are for x and y position (in integers) and third, fourth column for an arbitrary field value.

1 1 0.5 1.2 
1 2 1.7 2.3
1 3 2.0 2.2 
2 1 1.4 2.5
2 2 1.6 3.0
2 3 2.35 2.9
3 1 2.0 2.9
3 2 0.7 2.5
3 3 0.2 2.1

To this input file, I want to add two columns between second and third columns For each value of x,y in first two columns a z value from 1 to 3 should be added as a third column. Finally, a fourth column should be added with a value such that

if (z<$3 ) value = 0
if (z>=$3 && z <=$4) value = 1
if (z >$4) value = 2

note that $3 are $4 are the column values in the input file and $4 is always greater than $3.

The output file should look like

1 1 1 1 0.5 1.2 
1 1 2 2 0.5 1.2 
1 1 3 2 0.5 1.2 
1 2 1 0 1.7 2.3
1 2 2 1 1.7 2.3
1 2 3 2 1.7 2.3    
1 3 1 0 2.0 2.2 
1 3 2 1 2.0 2.2
1 3 3 2 2.0 2.2
2 1 1 2 1.4 2.5
2 1 2 2 1.4 2.5
2 1 3 2 1.4 2.5
2 2 1 0 1.6 3.0
2 2 2 1 1.6 3.0
2 2 3 1 1.6 3.0
2 3 1 0 2.35 2.9
2 3 2 0 2.35 2.9
2 3 3 2 2.35 2.9
3 1 1 0 2.0 2.9
3 1 2 1 2.0 2.9
3 1 3 2 2.0 2.9
3 2 1 1 0.7 2.5
3 2 2 1 0.7 2.5
3 2 3 2 0.7 2.5
3 3 1 1 0.2 2.1
3 3 2 1 0.2 2.1
3 3 3 2 0.2 2.1

How to create such output file with awk?

3

What you appear to be asking for is:

awk '{                 
  y = $2; 
  for(z=1;z<=3;z++){
     value = z < $3 ? 0 : z > $4 ? 2 : 1; 
    $2 = y OFS z OFS value; 
    print
  }
}' file

however I can't make it produce the output shown.

  • Thanks a lot for the answer. It works as expected ...! The discrepeny is due to the sample out file is not properly written. I will edit the sample file now. – alekhine Jul 31 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.