Q:

Reading file backward while using variable from first line

I want to read a file back ward while using a variable present in the first line (here: 2636).
My file:
nx_ 2355 ny_ 2636
0.000000 0.000000 0.000000
1.000000 68.000000 0.428139
2.000000 68.000000 0.939878
3.000000 67.000000 0.757181
4.000000 68.000000 0.000000
5.000000 69.000000 -1.229728

To read the file forward, and process it, I used:
cat $1 | awk 'NR==1 {nb=$4} NR>1 {up=nb-$1; print $2,up,$3}'

To read the file backward it seems I should use tac, but I don't know how to retrieve the variable in the first line, and avoid to process the last line.
I am searching for something like this:
tac $1 | awk 'NR==END {nb=$4} NR<END {up=nb-$1; print $2,up,$3}'

I want to have as output:
69.000000 2631 -1.229728
68.000000 2632 0.000000
67.000000 2633 0.757181
68.000000 2634 0.939878
68.000000 2635 0.428139
0.000000 2636 0.000000

A:

Is this what you're trying to do?
$ awk 'NR==1{nb=$4; next} {print $2, nb-$1, $3}' file | tac
69.000000 2631 -1.229728
68.000000 2632 0.000000
67.000000 2633 0.757181
68.000000 2634 0.939878
68.000000 2635 0.428139
0.000000 2636 0.000000

If you really did have to do what you said you wanted to do then that'd be this:
$ read -r _ _ _ nb < file; tail +2 file | tac | awk -v nb="$nb" '{print $2, nb-$1, $3}'
69.000000 2631 -1.229728
68.000000 2632 0.000000
67.000000 2633 0.757181
68.000000 2634 0.939878
68.000000 2635 0.428139
0.000000 2636 0.000000

or this:
$ read -r _ _ _ nb < file; tac file | awk -v nb="$nb" 'NR>1{print p[2], nb-p[1], p[3]} {split($0,p)}'
69.000000 2631 -1.229728
68.000000 2632 0.000000
67.000000 2633 0.757181
68.000000 2634 0.939878
68.000000 2635 0.428139
0.000000 2636 0.000000

or similar but it seems unlikely that's what you really need given the script you posted.
If the above doesn't answer your question then edit your question to clarify your requirements and provide the expected output given your posted sample input.

