2

I'm learning bash and I am stuck with data extraction from a text file. I know I can use "awk", but can't figure out how...

I have the following data organised in two columns.

8.044   FIX
9.326   3 the
18.726  blank
20.742  FIX
63.624  FIX
64.89   3 house
73.656  TEST

I would like to subtract the numbers shown in the first column, based on identifiers in the second column. "3" in the second column is my identifier and the subsequent line the number I would like to subtract from. So, it should be something like:

18.726 - 9.326
73.656 - 64.89

the output should be in a text file with three columns, like this:

9.326 9.4 1
64.89 8.766 1

Any help would be much appreciated! Thanks in advance!

2 Answers 2

1

Try :

awk '$2=="3"{out=1;last=$1;next}out{print last,$1-last,1;out=0}' infile
0

The awk code is a little easier if you reverse the lines of the file:

tac file | awk '$2 == "3" {print $1, prev - $1, 1} {prev = $1}' | tac
9.326 9.4 1
64.89 8.766 1

If "3" appears on the last line of the line, the 2nd value will be the 1st value negated: the "prev" variable will be empty, and awk will use the value zero in the subtraction.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .