Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add two variables in bash

Tags:

bash

shell

awk

I have a fileA that contains:

  0012,001650,0089

I want to get the sum of column 1 and column 2 and the quotient of column 3 and 60. Using awk I tried this

  col1=`awk -F, '{print $1}' $fileA | sed 's/0*//'`
  col2=`awk -F, '{print $2}' $fileA | sed 's/0*//'`
  col3=`awk -F, '{print $3}' $fileA | sed 's/0*//'`

  sum=$((col1 + col2))
  qou=$((col3 / 60))

But I got this error:

apn_processing.sh[226]: col1 + col2: The specified number is not valid for this command.

Can you give me another solution for this?

like image 440
starpark Avatar asked Sep 17 '25 08:09

starpark


2 Answers

shell is for sequencing calls to tools, that's all. If you're just doing text processing then do the whole job in awk:

$ awk -F, '{
  sum = $1 + $2
  quo = $3 / 60
  print sum, quo
}' "$fileA"
1662 1.48333
like image 56
Ed Morton Avatar answered Sep 19 '25 06:09

Ed Morton


You don't need to call awk 3 times to extract the fields:

$ IFS=, read -r a b c < file
$ echo $a
0012
$ echo $b
001650
$ echo $c
0089
$ echo $((10#$a + 10#$b))
1662
$ echo $((10#$c / 60))
1
$ bc  <<< "scale=3; $c/60"
1.483

In bash math, you can specific a number's base with the notation base#number, so you don't get tripped up by invalid octal numbers like "0089"

like image 39
glenn jackman Avatar answered Sep 19 '25 08:09

glenn jackman