3
#!/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...

4
  • well, your shebang indicates sh, not bash Commented Nov 17, 2011 at 19:51
  • Does it really have to be a shell script? I'm not trolling, just asking. Commented Nov 17, 2011 at 19:51
  • NOt sure what you are asking. Commented Nov 17, 2011 at 19:55
  • If this is homework for school, you should tag it as such. Good luck. Commented Nov 17, 2011 at 20:24

3 Answers 3

2

It sounds like you want something like:

$ awk '{x[$1] += $2} END {for( i in x) print i, x[i]}' input-file
Sign up to request clarification or add additional context in comments.

3 Comments

Le mort saisit le vif. I <3 awk on occasion.
Tiens un Français. Mais je comprend pas pour autant l'expression.
@sputnick: Je pense que l'idée est quelque chose comme 'Le Roi est mort, vive le Roi !'
0
#!/usr/bin/env bash

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

2 Comments

Yes "it works", but you spawn a useless process. awk read files itself ;)
im trying to add this code you gave me but its not working im new to bash,may you help me with a sample script or where to put it in my code..thanks
0
#!/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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.