2011-11-17 124 views
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 

我試圖代碼在bash腳本什麼的,我有一個txt文件,我進入了它的名稱如下如陣列在bash shell腳本

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 

我希望有一個代碼或環當我運行該程序時,它應該顯示在txt文件上的名稱,並顯示總數,如果lex出現7次,凱萊3次,它會顯示lex 52.5 gloria-3等。我不知道你是否得到我的想法...

+0

好吧,你的shebang表示'sh',而不是'bash' – c00kiemon5ter

+0

它是否真的必須是shell腳本?我不是在拖釣,只是問。 –

+0

你的問題是什麼? –

回答

0
#!/usr/bin/env bash 

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

貓| awk?無用的貓使用。請參閱http://partmaps.org/era/unix/award.html –

+0

不必要?當然。無用?不。有用。 –

+0

是「有效」,但你產生了一個無用的過程。 awk讀取文件本身;) –

2

聽起來像你想要的東西:

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

Le mort saisit le vif。我有時候<3 awk。 –

+0

Tiens unFrançais。 Mais je comprend pas pour autant l'expression。 –

+0

@sputnick:Je pense que l'idéeest quelque選擇了「Le Roi est mort,vive le Roi!」 – jlliagre

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 

是這樣的嗎?取決於兩個由空格分開的字段,而數字前加+或 - 。