Lukáš Altman
Lukáš Altman

Reputation: 527

How to add numbers from files to computation?

I need to get results of this formula - a column of numbers

{x = ($1-T1)/Fi; print (x-int(x))} 

from inputs file1

4  4
8  4
7  78
45 2

file2

0.2
3
2
1

From this files should be 4 outputs. $1 is the first column from file1, T1 is the first line in first column of the file1 (number 4) - it is alway this number, Fi, where i = 1, 2, 3, 4 are numbers from the second file. So I need a cycle for i from 1 to 4 and compute the term one times with F1=0.2, the second output with F2=3, then third output with F3=2 and the last output will be for F4=1. How to express T1 and Fi in this way and how to do a cycle?

awk 'FNR == NR { F[++n] = $1; next } FNR == 1 { T1 = $1 } { for (i = 1; i <= n; ++i) { x = ($1 - T1)/F[i]; print x - int(x) >"output" FNR} }' file2 file1

This gives more than 4 outputs. What is wrong please?

Upvotes: 1

Views: 55

Answers (1)

oguz ismail
oguz ismail

Reputation: 50750

  1. FNR == 1 { T1 = $1 } is being run twice, when file2 is started being read T1 is set to 0.2,
  2. >"output" FNR is problematic, you should enclose the output name expression in parentheses.

Here's how I'd do it:

awk '
  NR==1 {t1=$1}
  NR==FNR {f[NR]=$1; next}
  {
    fn="output"FNR
    for(i in f) {
      x=(f[i]-t1)/$1
      print x-int(x) >fn
    }
    close(fn)
  }
' file1 file2

Upvotes: 2

Related Questions