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?
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With