Dividing a column by it's last number

Hi!

I have a file as below:

0.000145 5.82056e-08
0.000146 6.82088e-08
0.000150 7.42115e-08
0.000156 8.52142e-08
0.000176 8.82169e-08
0.000178 9.82197e-08

I'd like to divide the values of the second column by its last entry (here 9.82197e-08).
I would be thankful if someone could show me how to do it in Linux.
Thanks!

Please use code tags as required by forum rules!

"Do it in Linux" is somewhat ambiguous. Do you want to deploy a shell script, an awk (or other tool) script? Any attempts/thoughts/ideas from your side?

Sorry, I should have been more clear.
I searched in the forum and I saw a similar post as mine by for dividing a column by its first number using awk. here is what was suggested:

awk 'BEGIN{first_line=0;divide_by=1;}{if(first_line==0){first_line=1; divide_by=$1;}print $1/divide_by;}END{}' your_file

Now, I'm wondering how I can do the same but by dividing the column by its last number.

Hi, try:

awk 'NR==FNR{n=$2; next} {$2/=n}1' your_file your_file

output:

0.000145 0.592606
0.000146 0.694451
0.000150 0.755566
0.000156 0.867588
0.000176 0.898159
0.000178 1

You could add testing for n==0

---

Note: the input file must be specified twice on the command line !

There are several possible approaches. For small files like above, you can keep all input in memory, try

awk '{T1[NR] = $1; T2[NR] = $2} END {for (n=1; n<=NR; n++) print T1[n], T2[n]/$2}' file
0.000145 0.592606
0.000146 0.694451
0.000150 0.755566
0.000156 0.867588
0.000176 0.898159
0.000178 1

This may work on some but not all awk versions depending on the NR and $2 values being retained in the END section or not.
For larger files, you might want to extract the last line with e.g. tail , or reverse the overall line order with tac , or run through the file twice.

1 Like

@RudiC, according to POSIX awk:Variables and Special Variables

So one should be able to use NR and instead of $2 , you could use T2[NR]

Many thanks Rudi!

Actually my file is large (I had just put a sample of the last rows). But anyways it works perfectly now!