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.

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.