thequantumtheories
thequantumtheories

Reputation: 120

Arrays in bash shell scripts

#!/bin/sh
# Script to count the total in an array
# Define the name of the file
#
fname=names.txt

# Read in the contact details from the keyboard
echo "Please enter the following contact details:"
echo
echo "Given name: \c"
read name
echo " value: \c"
read value
# Write the details to the text file
echo $name:$value >> $fname

I'm trying to code something in bash scripting, I have a txt file and I entered the following names on it e.g

lex +7.5
creg +5.3
xondr/xonde +1.5
gloria-1
lex +7.5
gloria -1
creg +5.3
xondr/xonde +1.5
lex +7.5
#and so on

I want a code or a loop that when I run the program it should show the names of that are on the txt file and show there total,if lex appears 7 times and gloria 3 times it will show lex 52.5 gloria-3 etc. I don't know if you get my idea...

Upvotes: 3

Views: 849

Answers (3)

Rob Cowie
Rob Cowie

Reputation: 22619

#!/usr/bin/env bash

awk '{people[$1] += $2} END {for (person in people) 
{ printf("%s %10.2f\n",person,people[person])}}' test.txt

Upvotes: 0

ata
ata

Reputation: 2065

#!/bin/bash
declare -A names
declare name num

#sum
while IFS=" " read name num; do
    names[$name]=$( bc <<< "${names[$name]:-0}$num" )
done

#print
for name in ${!names[@]}; do
    echo "$name: ${names[$name]}"
done

Something like this? Depends on the two fields being separated by space and the numbers being prepended with + or - though.

Upvotes: 0

William Pursell
William Pursell

Reputation: 212208

It sounds like you want something like:

$ awk '{x[$1] += $2} END {for( i in x) print i, x[i]}' input-file

Upvotes: 2

Related Questions