bash - 根据条件

时间:2017-05-12 18:22:03

标签: bash awk

我确定必须在某个地方回答,但我不太清楚如何搜索我的问题。

我有一个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 ...

1 个答案:

答案 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