0

I am writing a script that's picking up two values from a file and then subtracting them.But I am unable to do substraction as it is throwing error.

   res1=  awk 'FNR == '${num1}' {print $1}' /home/shell/test.txt
   res2=  awk 'FNR == '${num2}' {print $1}' /home/shell/test.txt

   res= $((res2 - res1))
   echo $res

I also tried expr = `expr $res2 -$res1` but it didn't work. please help me so as to get the desired result.

tripleee
  • 175,061
  • 34
  • 275
  • 318
Ashu
  • 61
  • 7
  • 1
    Possible duplicate of [Subtract 2 variables in Bash](http://stackoverflow.com/questions/8385627/subtract-2-variables-in-bash) – arved May 09 '16 at 18:32

2 Answers2

1

your assignments for res1/res2 are wrong. It should be

res1=$(awk 'FNR == '${num1}' {print $1}' /home/shell/test.txt)

However, you can do it all in awk

$ num1=5; num2=2; awk -v n1=${num1} -v n2=${num2} 'FNR==n1{r1=$1;f1=1}
                                                   FNR==n2{r2=$1;f2=1}
                                                    f1&&f2{print r1-r2; exit}' <(seq 5)
3
karakfa
  • 66,216
  • 7
  • 41
  • 56
0

This is because there is one space char after each = sign: res1= awk

Remove the spaces and use $( command ) to execute a command and gather its output.

Give a try to this:

res1="$(awk -v num=${num1} 'FNR == num {print $1}' /home/shell/test.txt)"
res2="$(awk -v num=${num2} 'FNR == num {print $1}' /home/shell/test.txt)"
res=$(( res2 - res1 ))
printf "%d\n" ${res}

I had read in another answer that it is preferred to pass variable's value to awk script using -v var_name=value, rather than concatenating strings.

Jay jargot
  • 2,745
  • 1
  • 11
  • 14