Print a file and substract in two rows

0

0

I would like to print and substract in each two rows from a file

toto 30
tata 20
toto 12
tata 6
toto 22
tata 8

the output :

diff : 10
diff : 6
diff : 14

I find a script :

FILENAME=$1

while read line
do
  if [ -n "$prevLine" ]
  then
    curLine=$line
    echo $(($curLine - $prevLine))
  fi
  prevLine=($line)
done < $FILENAME

I would like to read line+1 to make a range of 2

tumareure

Posted 2019-07-16T13:46:31.433

Reputation: 3

1You will need to read the file using a loop. – FedonKadifeli – 2019-07-16T13:49:40.113

Your script is on the right lines. Add a line counter which is incremented on each loop pass and check whether $(($lineNo%2)) is zero to decide when difference is to be calculated and printed. – AFH – 2019-07-16T14:00:53.510

I don't understand you solution, Can you have a code to propose me ? – tumareure – 2019-07-16T14:03:26.197

Answers

0

With sole awk:

<file awk '{if ($1=="toto") old=$2; else if ($1=="tata") print "diff : " old-$2}'

where file is the file with your data. For each "tata" line the command will print the difference from the previous "toto" line.

Or if it's about odd and even lines (regardless of "toto"/"tata"), then this:

<file awk '{if (NR%2==1) old=$2; else print "diff : " old-$2}'

Kamil Maciorowski

Posted 2019-07-16T13:46:31.433

Reputation: 38 429