#!/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文件,我在其上输入了以下名称,例如
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次而gloria 3次将显示lex 52.5 gloria-3我不知道你是否明白我的想法......
答案 0 :(得分:2)
听起来你想要这样的东西:
$ awk '{x[$1] += $2} END {for( i in x) print i, x[i]}' input-file
答案 1 :(得分: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
这样的东西?取决于两个字段由空格分隔,数字前面加上+或 - 但是。
答案 2 :(得分:0)
#!/usr/bin/env bash
awk '{people[$1] += $2} END {for (person in people)
{ printf("%s %10.2f\n",person,people[person])}}' test.txt