Find total of a column of numbers with BASH

Find total of a column of numbers with BASH

Created:28 Nov 2016 20:53:05 , in  Host development

Problem: Find total of numbers in a file.

File 1:


aaa:23
bb:2
ccc:98
.
.
.

File 2:


23,aaa
2,bb
98,ccc
.
.
.

File 3:


aaa,23,aaa
ccc,2,bb
bb,98,ccc
.
.
.

Function to find the total


#!/usr/bin/env bash
 
function sum_it_up(){
  file="${1}"
  delimiter=${2:-":"}
  field=${3:-"2"}
  sum=0
  ints=($(cut -d ${delimiter} -f"${field}" "${file}"))
  for num in "${ints[@]}";do ((sum+=num)); done; echo $sum;
}

sum_up "${1}" "${2}" "${3}"

Usage for File 1:


$ ./sum_it_up.sh to_sum_up.txt

Usage for file 2:


$ to_sum_up.txt "," 1

Usage for file 3:


$ ./sum_it_up.sh to_sum_up.txt "," 2

Parameters the function accepts are: file to process, [delimiter to split columns in the file at] (default is ":"), [column number to sum up] (default is 2).

Use loop to find the total


# initial total
total=0
# column separator 
ifs=,
# column to find total of
col=col2
# data file
data_file=data

while IFS="$ifs" read -r col1 col2 col3 ; do
  (( total+=$"$col" ))
done < "$data_file"

echo $total

Use an array


# initial total
total=0
# column separator 
ifs=,
# column to find total of
index=2
# data file
data_file=data

while IFS="$ifs" read -r -a cols ; do
  (( total+=${cols[ $index - 1 ]} ))
done < "$data_file"

This post was updated on 06 Oct 2021 20:16:44

Tags:  BASH 


Author, Copyright and citation

Author

Sylwester Wojnowski

Author of the this article - Sylwester Wojnowski - is a sWWW web developer. He has been writing computer code for the websites and web applications since 1998.

Copyrights

©Copyright, 2022 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.

Computer code, if present in the article, is excluded from the above and licensed under GPLv3.

Citation

Cite this article as:

Wojnowski, Sylwester. "Find total of a column of numbers with BASH." From sWWW - Code For The Web . https://wojnowski.net.pl//main/index/find-total-of-a-column-of-numbers-with-bash

Add Comment

Allowed BB Code - style tags: [b][/b], [i][/i], [code=text][/code],[code=javascript][/code],[code=php][/code],[code=bash][/code],[code=css][/code],[code=html][/code]


I constent to processing my data given through this form for purposes of a reply by the administrator of this website.

Recent Comments

Nobody has commented on this post yet. Be first!