2

I have two files of the form

file1:

#fileheader1
0 123
1 456
2 789
3 999
4 112
5 131
6 415
etc.

file2:

#fileheader2
0 442
1 232
2 542
3 559
4 888
5 231
6 322
etc.

How can I take the second column of each, divide it by a value then minus one from the other and then output a new third file with the new values?

I want the output file to have the form

#outputheader
0 123/c-422/k
1 456/c-232/k
2 789/c-542/k
etc.

where c and k are numbers I can plug into the script

I have seen this question: subtract columns from different files with awk

But I don't know how to use awk to do this by myself, does anyone know how to do this or could explain what is going on in the linked question so I can try to modify it?

Community
  • 1
  • 1
Pigeon
  • 125
  • 5

1 Answers1

2

I'd write:

awk -v c=10 -v k=20 '                        ;# pass values to awk variables
    /^#/ {next}                              ;# skip headers
    FNR==NR {val[$1]=$2; next}               ;# store values from file1
    $1 in val {print $1, (val[$1]/c - $2/k)} ;# perform the calc and print
' file1 file2

output

0 -9.8
1 34
2 51.8
3 71.95
4 -33.2
5 1.55
6 25.4
etc. 0
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Thanks, the comments help a lot! When I put this in a file and try to run it with "awk -f test.awk" however it gives me syntax error near line 1? – Pigeon Dec 08 '14 at 21:18
  • Did you copy my whole code into your awk script, including the `awk -v` line? – glenn jackman Dec 08 '14 at 21:18
  • @Pigeon, the given answer is meant to be run as-is from the command line. It is not itself an awk file to use with -f. If you prefer to externalize the awk commands into a file to use with -f, just take what's within the single quotes (not including the quotes). – jas Dec 08 '14 at 21:42