user5578188
user5578188

Reputation: 63

Linux: get the last number of each line with a certain pattern and add those numbers up and save it as a variable

I am trying to be able to write a command that will get the last numbers of each platform and add them up then save that number as a variable. For example, for "AIX" in the below random file, I want to be able to extract 1 and 115 and save 116 as a variable. Then for "Linx" I would want to save 2, 16, 18, 96 and 1 and save the sum as another variable.

cat randomfile.txt:

AIX,5.5.3-0,1
AIX,6.2.1-0,115
Linux x86-64,6.4.0-0,2
Linux x86-64,6.4.0-1,16
Linux x86-64,7.1.2-0,18
Linux86,6.1.3-4,96
Linux86,6.2.5-0,1

I was able to use "cat randomfile.txt | egrep "Linux" ", to specify only Linux lines although I need a way to print the last numbers of each line so I can save them into a variable and then add them up and save them as one variable.

Upvotes: 0

Views: 687

Answers (3)

Joe
Joe

Reputation: 917

> numbers=$(grep Linux randomfile.txt | cut -d, -f3)
> sum=$(( ${numbers//$'\n'/+} ))
> echo $sum
133

grep provides the matching lines (Linux,AIX, …) and the cut command returns the numbers after the second comma. Then the pattern /$'\n' is used to replace every newline in the $numbers variable with + giving 2+16+18+96+1 for Linux.

Then arithmetic expansion $((…)) is used to evaluate that summation and store the result in $sum.

(see also https://stackoverflow.com/a/13969439/4832389)

Upvotes: 0

James Brown
James Brown

Reputation: 37394

How about awk to an array?:

$ a=($(awk -F, '{sub(/[ 0-9].*/,"",$1);a[$1]+=$3}END{for(i in a)print i "=" a[i]}' file))
$ echo ${a[0]}
AIX=116
$ echo ${a[1]}
Linux=133

Upvotes: 1

JNevill
JNevill

Reputation: 50019

You can use to go at this file:

variable1=$(awk -F, '$1=="AIX"{aixsum+=$NF} END{print aixsum}' file)
variable2=$(awk -F, '$1~/^Linux/{linuxsum+=$NF} END{print linuxsum}' file)

That first one splits each record by comma and tests the first field. If it's equal to "AIX" it will sum up the last field into awk variable aixsum. Once it's processed the file it will spit out the result with that END{} block.

The second one works similar but uses regex for the search and finds any record where the first field starts with "Linux" and sums up the last fields, printing it once it has read the entire file.

Upvotes: 2

Related Questions