Как с помощью awk добавить элементы в одну строку в разных записях?

Вероятно, более быстрым инструментом является awk. Использование строки [END]как R запись S разделитель:

awk -vRS='\\[END\\]' -vORS='[END]\n' '/\"AAA\"/' infile | 
awk '/output:$/,/\[END\]/'

В первой строке выбираются записи R , которые содержат "AAA".
Вторая строка ограничивает вывод строками между output:и [END].

0
07.11.2019, 20:56
4 ответа

Awk подход:

$ awk '{ cat=$(NF-1); a[cat] += $NF; sum += $NF; b[cat]++ }
       END{ for (cat in a) print cat, a[cat]/b[cat]; print "all avg", sum/NR }' file

Выход:

dairy 2.5
produce 1.735
pastries 0.74
all avg 1.77857
2
28.01.2020, 02:29

First, I want to add all prices in the file together, then find the average. I should have the output of 1.78 (rounded up).

Обратите внимание, что NRсодержит текущий номер строки при обработке файла, в предложении ENDон сообщит вам общее количество строк, например.:

awk '{ sum+=$3 } END { print sum, sum/NR }'

Или с округленными числами:

awk '{ sum+=$3 } END { print sum, sum/NR }' OFMT='%.2f'

Second, I want to add the prices of all dairy products, and find the average price of the dairy products. In this case, my output should be 2.50.

Вы почти не используете какие-либо встроенные -возможности, поставляемые с awk, например. каждое утверждение состоит из boolean_expression { actions }. Таким образом, действовать только в тех строках, где$2 == "dairy":

awk '$2 == "dairy" { sum+=$3; count++ } END { print sum, sum/count }'
0
28.01.2020, 02:29

Поскольку ОП запросил некоторые пояснения, вот попытка сделать это. Ответ основан на ответе Романа Перехреста, но немного отличается.

#!/bin/awk -f

{ 
    products = $2 # Store the second field in products
    a[products] += $NF # Increment each item in the array. $NF denotes the last field. 
    total += $NF # This is the total count of the last field all together resulting in a total of:  12.45
    pr[products]++  #increment by 1 if item found in second field. For dairy this should be 3
} 
END { 
    for (products in a)  # for loop
      print products, a[products] / pr[products]  # print product name, total of products / products found
      printf("All avg: %.2f\n", total/NR); # Print average of all products. So 12.45 / 7 = 1.778571
}

Вызовите скрипт следующим образом:

chmod u+x myawkscript.awk &&./myawkscript.awk inputfile 
0
28.01.2020, 02:29

Общее среднее значение продукта

total_number_of_produts=`awk 'END{print NR}' filename`

awk -v t0="$total_number_of_produts" 'BEGIN{sum=0}{sum=sum+$NF}END{print sum/t0}' filename

output
1.777 (1.78)

В среднем по молочным продуктам

da=`awk '/dairy/{print NR}' filename | wc -l`

awk -v t0="$total_number_of_produts" 'BEGIN{sum=0}{sum=sum+$NF}END{print sum/t0}' filename 


output
2.5
0
28.01.2020, 02:29

Теги

Похожие вопросы