Chubaka
Chubaka

Reputation: 3135

pass awk calculation results to variables

Let's say we have an input file_789

1
1
1

Is there any way that we could output the awk counting results into variables so that we can print out the following?

Cargo 789 has 3 items

Now we try:

for cargo in 789

do

awk '{ sum+=$1} END {print sum}' file_${cargo}  # This will give us a result of "3". 

echo "Cargo ${cargo} has ${calculation} items" 

done

Wonder if there is any way to pass the awk one liner result to ${calculation} so echo could do its work? Thanks~!

Upvotes: 1

Views: 1026

Answers (1)

John1024
John1024

Reputation: 113834

The awk calculation can be stored in a shell variable:

calculation=$(awk '{ sum+=$1} END {print sum}' "file_${cargo}")

Or, you can do both the calculating and printing in awk:

awk '{ sum+=$1} END {print "Cargo '"${cargo}"' has " sum " items"}' "file_${cargo}"

Alternatively, we can use printf which works better with empty files:

awk -v cargo="$cargo" '{sum+=$1} END {printf "Cargo %s has %d items\n", cargo, sum}' "file_${cargo}"

Also, the use of the option -v cargo="$cargo" simplifies the quoting.

Upvotes: 2

Related Questions