5

I have two long files that have the repeating general structure,
File1:
AA 100
BB 10
File2:
AA 100
BB 1

I want to subtract column 2 from even lines of File2 from File1, but maintain/print the other information so it remains.
Desired output:
AA 100
BB 9

For which I have written the awk:
awk '{a=$2;getline<f;$2-=a}!(NR % 2)' f=File1 File2

This produces:
BB 9
Which does the subtraction and prints the result fine, but I'm having trouble adding in the other data.

How can I also print the other data alongside this subtraction?

2 Answers 2

5
$ paste file1 file2 | awk '{print $1, $2 - (NR%2 ? 0 : $4)}'
AA 100
BB 9

or if you wanted an awk-only solution:

$ awk 'NR==FNR{if (!(NR%2)) a[NR]=$2; next} {$2 -= a[FNR]} 1' file2 file1
AA 100
BB 9

If you were considering using getline for this, please read http://awk.freeshell.org/AllAboutGetline so you're aware of the issues around doing so.

3

Something like this?

awk '{a=$2;getline<f;(NR%2)?$2:$2-=a;print}' f=File1 File2

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.