awk Array Combat

Source: Internet
Author: User

1, Array summation

Topic 1:

The contents of the known file are as follows:

[email protected] ~]# cat Awk1.txt
1
2
3
4
5
6
7
8
9

[[email protected] ~]# awk ' {array[1]+=$1}end{for (key in array) print Array[key]} ' awk1.txt
45

Topic 2:

The contents of the known file are as follows:

[email protected] ~]# cat Awk2.txt
Zhangsan 80
Lisi 81.5
WANGWU 93
Zhangsan 85
Lisi 88
WANGWU 97
Zhangsan 90
Lisi 92
WANGWU 88

Required output format: (Name: Name average: Average total: Overall score)

Answer:

[[email protected] ~]# awk ' {array[$1]+=$2;array1[$1]++}end{for (key in array) print "Name:" Key "\taverage:" array[key]/ Array1[key] "\ttotal:" Array[key]} ' awk2.txt
Name:zhangsan average:85 total:255
Name:lisi average:87.1667 total:261.5
Name:wangwu average:92.6667 total:278

2. File Merging

Topic 1:

Known file contents are as follows

[email protected] ~]# cat Filea.txt
Han Hailin 21 years old
Hailin Korea 23 years old
Han Linhai 22 years old
Lin Hai Han 24 years old
[email protected] ~]# cat Fileb.txt
Han Linhai Male
Hailin Han Ju
Han Hailin Women
Linhai Han Nan


Use the awk command to merge the two lines with the same name in the following two files.

Answer:

[[email protected] ~]# awk ' {if (NR! = FNR) {arrayb[$1]=$2}else {arraya[$1]=$2}}end{for (key in Arraya) print Key,arraya[key ],arrayb[key]} ' Filea.txt fileb.txt
Han Hailin 21-year-old woman
Hailin Korean 23 year old woman
Han Linhai 22-year-old male
Lin Hai Han 24 year old man



This article is from the "architects of the Day" blog, be sure to keep this source http://wanyuetian.blog.51cto.com/3984643/1717133

awk Array Combat

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.