我确定必须在某个地方回答,但我不太清楚如何搜索我的问题。
我有一个X行数的文件:
fruit=orange origin=spain seller=walmart amount=10
fruit=banana origin=colombia seller=walmart amount=5
fruit=apple origin=france seller=target amount=3
fruit=orange origin=spain seller=target amount=4
fruit=orange origin=spain seller=walmart amount=4
fruit=apple origin=spain seller=walmart amount=90
我想要做的是循环遍历这些行,将具有相同fruit
值的所有行捆绑在一起并计算总amount
。扭曲的是,我无法事先告诉fruit
中的值。
这是我到目前为止所得到的:
cat fruits.txt |
while read data
do
for i in "$data"; do
if [[ some condition]]; then
echo $i >> fruits2.txt
fi
done
done
我意识到我必须遍历每一行并在满足条件时保存它。但是如何保持循环,直到迭代完所有行并将数量加在一起?
我期待的输出应该是这样的:
Fruit Amount
orange 18
apple 93
etc ...
答案 0 :(得分:3)
使用Awk
非常简单,只需设置一个多字符限制器来解析行[= ]
中的单词,即=
符号和单个空格,完成后,$2
成为水果名称,$NF
成为水果计数。有了这个设置,你需要做的就是,
awk -F'[= ]' '{fruitCount[$2]+=$NF; next}END{for (fruit in fruitCount) printf "Count of %s is %s\n",fruit,fruitCount[fruit]}' file
生成输出
Count of orange is 18
Count of apple is 93
Count of banana is 5
(或)以OP希望的格式打印,
awk -F'[= ]' 'BEGIN{printf "Fruit\tAmount\n"}{fruitCount[$2]+=$NF; next}END{for (fruit in fruitCount) printf "%s\t%s\n",fruit,fruitCount[fruit]}' file
应该给你,
Fruit Amount
orange 18
apple 93
banana 5
OP希望将输入作为水果并返回该水果的数量。它应该与read
命令一起使用并在Awk
命令中导入它。在bash
脚本中,
#!/usr/bin/bash
read -p "Enter fruit name: " fruitName
awk -F'[= ]' -v fruit="${fruitName}" 'BEGIN{printf "Fruit\tAmount\n"}$2 ~ fruit {fruitCount[$2]+=$NF; next}END{for (fruit in fruitCount) printf "%s\t%s\n",fruit,fruitCount[fruit]}' file
并以bash script.sh
运行脚本。一些样本结果,
$ bash script.sh
Enter fruit name: orange
Fruit Amount
orange 18
$ bash script.sh
Enter fruit name: apple
Fruit Amount
apple 93
$ bash script.sh
Enter fruit name: banana
Fruit Amount
banana 5