使用awk或grep在文件中添加特定数字

时间:2014-12-29 22:42:26

标签: awk sed grep

我正在寻找类似的东西:

文件名:fruites.txt

Apple a day keeps doctor away
but people dont like it............... 23 peoples found.

Banana_A.1 keeps u fit 
and its very tasty.................... 12 peoples found.

Banana_B.2 juices is very good to taste
and most people like them
as well as consumed the most.......... 15 peoples found.

Anar is difficult to eat
as well as its very costly............ 35 peoples found.

grapes are easy to eat
and people like it the most........... 10 peoples found.

fruites are very healthy and improves vitamins.

Apple : The apple tree is a deciduous tree in the rose family best known for its sweet, pomaceous    
fruit, the apple.

Banana_A.1: A banana is an edible fruit, botanically a berry, produced by several kinds of large  
herbaceous flowering plants in the genus Musa.

Banana_B.2: A banana is an fruit, botanically a kerry, produced by several kinds of large  
herbaceous flowering plants in the genus Musa.

Anar :  The pomegranate, botanical name Punica granatum, is a fruit-bearing deciduous shrub or  
small tree growing between 5 and 8 m tall. 

除了香蕉外,我想要添加所有人物

ANS:68(23 + 35 + 10)

我可以单独找到计数,但无法减去它们

我试过这个

grep -E“.found”fruites.txt | awk'{sum + = $ 3} END {print sum}'

ANS:95(68 + 27)

grep -E“香蕉| .found”fruites.txt | grep -A1“香蕉”| grep -E“.found”| awk'{sum + = $ 3} END {print sum}'

AND:27(只有香蕉)

任何人都可以请帮助

2 个答案:

答案 0 :(得分:2)

awk '$1 != "Banana" {s+=$(NF-2)} END { print s}' RS= fruites.txt

这里的关键是RS=赋值,它使awk将由空行分隔的每个文本部分视为单独的记录。请注意,为了清楚起见,您可能更愿意编写RS="" fruites.txt,但这不是必需的。但是,请确保不要在=之后省略空格,因为关键是将空字符串作为RS的值。

- 编辑 -

鉴于评论和修改过的问题,也许你想要:

awk '! match($1,"Banana") && match($NF, "found") {
    s += $(NF-2)} END { print s }' RS= fruites.txt

答案 1 :(得分:0)

您可以使用以下awk命令。

$ awk -v RS="\n\n" '!/Banana/ && /peoples found\.$/{s+=$(NF-2)} END { print s}' file
68

上面的awk命令将空行\n\n设置为Record seperator值,并检查Banana字符串是否不存在以及最后是否存在peoples found.字符串。如果满足两个条件,则仅计算最后一列的第三列的总和。因此s+=$(NF-2)也写为s = s + $(NF-2)包含总和。在最后打印s的值将为您提供总和。