LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   preserving last read value in shell script (https://www.linuxquestions.org/questions/linux-newbie-8/preserving-last-read-value-in-shell-script-863059/)

jkeertir 02-16-2011 08:52 AM

preserving last read value in shell script
 
Dear ALL,

Here are the contents of the file
1600
1900
2200
2800

I want to read file content using shell script
and check if the difference between the two line count is 300

With regards,
Keerti

druuna 02-16-2011 09:54 AM

Hi,

Code:

#!/bin/bash

PrevValue="-1"

for ThisValue in $(cat infile)
do
  if [ ! $PrevValue = "-1" ]
  then
    let SubtValue=ThisValue-PrevValue
    if (( SubtValue == 300 ))
    then
      echo "difference is 300 ($ThisValue - $PrevValue)"
    else
      echo "difference is not 300 ($ThisValue - $PrevValue)"
    fi
  fi
  let PrevValue=ThisValue
done

Hope this helps.

grail 02-16-2011 10:35 AM

Or another option:
Code:

awk 'NR > 1{printf "Difference is %s300\n",($0 - x == 300)?"":"not "}{x = $0}' file

jkeertir 02-16-2011 10:52 AM

Thanks
 
Thanks druuna,it worked for me

druuna 02-16-2011 10:53 AM

You're welcome :)

rdgreenlaw 02-16-2011 11:05 AM

I created a script named readfile and a test data file named testdata. Testdata contains all the data in your sample.

Code:

#!/bin/bash
read var1
echo "variable 1 is: $var1"
let var3=0
echo "Variable 3 is: $var3"
let check=0

while read var2 ; do
  echo "Variable 2 is: $var2"
  var3=$(expr $var2 - $var1)
  echo "Variable 3 is computed as var2 - var1: $var3"
  let var1=var2
  echo "Variable 1 now set to value of variable 2"
  echo "Variable 1 is $var1 Variable 2 is $var2 Variable 3 is $var3"
  echo "loop for more records"
done

echo "Read completed"

Note: I don't do testing to verify the data, I'm assuming you know how to do that. This script simply shows the process of reading the data and uses echo to display messages and values that demonstrate the process the loop is going through.

Hope this helps!

Roger


All times are GMT -5. The time now is 03:42 AM.