The question is published on by Tutorial Guruji team.
I have the following piece of code:
sum1= sum2= declare -a a echo $temp | awk '{split($0,a,","); name=a[1] ; for(i=2;i<=4;i++) sum1+=a[i] ; for(i=5;i<=7;i++) sum2+=a[i] }'
This code is not working. Here temp is a string of type:
abc,1,2,3,4,5,6
Actually I am parsing data from a file. The input file is like:
abc,1,2,3,4,5,6 de,3,5,7,8,4,2 xyz,6,5,3,7,8,2
I am reading it using
while read temp do #do something done < sample.csv
And expected output is of the form:
Name Sum1 Sum2 abc 6 15 de 15 14 xyz 14 17
Answer
Setting up $temp
First be sure that you’ve set up the $temp
variable properly:
$ temp="abc,1,2,3,4,5,6" $ echo "$temp" abc,1,2,3,4,5,6
Simple example
I used the following approach to do it:
$ echo "$temp" | tr ',' 'n' | grep -v abc | awk '{sum+=$1};END{print sum}' 21
Your example
Regarding your approach you forgot to print the arrays you accumulated with an END{...}
block:
$ echo "$temp" | awk '{split($0,a,","); name=a[1] for(i=2;i<=4;i++) sum1+=a[i] ; for(i=5;i<=7;i++) sum2+=a[i] } END{print sum1; print sum2}' 6 15
Saving for later
Awk doesn’t have a method for injecting results back into the parent’s shell from where it was called, so you’ll have to get a bit crafty and save it’s results to an array in Bash.
Example
$ myarr=($(echo "$temp" | awk '{split($0,a,","); name=a[1] for(i=2;i<=4;i++) sum1+=a[i] ; for(i=5;i<=7;i++) sum2+=a[i] } END{ print sum1; print sum2}'))
The above is doing this:
$ myarr=($(...awk command...))
This will result in your values from sum1
and sum2
being saved into array $myarr
.
Accessing the array $myarr
They’re accessible like so:
$ echo "${myarr[@]}" 6 15 $ echo "${myarr[0]}" 6 $ echo "${myarr[1]}" 15