3

I have a 3 column text file (XYZ coordinates) and I need to iteratively add constants to the first column while appending to the end of the original file. I have tried several options but this is the one that gives the clearest idea of what I'm trying to do:

awk ' { for ( i=-4; i<=4; i+=2 ) $1+=i }' coords.txt >> new_coords.txt

This command results in a blank new_coords.txt file. How do I go about getting the output of the for loop into the new text file?

Minimal Input

4 5 6 
7 8 9

Minimal Output

0 5 6
3 8 9 
2 5 6 
5 8 9
4 5 6
7 8 9
6 5 6
9 8 9
8 5 6
11 8 9
1

I think this may be one of the (rare) cases when it actually makes sense to put the loop outside of Awk:

$ for ((i=-4;i<=4;i+=2)); do awk -v i="$i" '{$1+=i} 1' Input; done
0 5 6
3 8 9
2 5 6
5 8 9
4 5 6
7 8 9
6 5 6
9 8 9
8 5 6
11 8 9

Otherwise:

$ awk '{a[NR] = $1; b[NR] = $2 FS $3} END{for(i=-4;i<=4;i+=2){for(j=1;j<=NR;j++) print a[j]+i, b[j]}}' Input 
0 5 6
3 8 9
2 5 6
5 8 9
4 5 6
7 8 9
6 5 6
9 8 9
8 5 6
11 8 9
  • Very nice, thank you! – Brady W. May 17 at 23:28

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.