Awk array for Linux learning

Array definition:

An array is an associated variable, which can be accessed sequentially through subscripts.
Array name[subscript] = value, the subscript can use numbers or strings.

Array traversal:

for(variable in array name) { array name[variable] operation }

Array deletion:

delete array name, you can delete the entire array
delete array name [subscript], you can delete a certain array element

echo 'zhaoy 70 72 74 76 74 72' >> score.txt
echo 'wangl 70 81 84 82 90 88' >> score.txt
echo 'qiane 60 62 64 66 65 62' >> score.txt
echo 'sunw 80 83 84 85 84 85' >> score.txt
echo 'lixi 96 80 90 95 89 87' >> score.txt

Write the following content into score.txt:

zhaoy 70 72 74 76 74 72
wangl 70 81 84 82 90 88
qiane 60 62 64 66 65 62
sunw 80 83 84 85 84 85
lixi 96 80 90 95 89 87

insert image description here
awk '{sum=0;for(col=2;col<NF;col++) sum=sum+$col;allSum[$1]=sum}END{print allSum["zhaoy"]}' score.txtzhaoyThe total score can be seen 366. NFYes awk, system variables, if you don't know the meaning, you can refer to the system variables in the blog post "Awk Expressions for Linux Learning" .
insert image description here

awk '{sum=0;for(col=2;col<NF;col++) sum=sum+$col;allSum[$1]=sum}END{for(user in allSum) print user,allSum[user]}' score.txtCalculate the sum of the user's grades, store them allSumin the array, and ENDoutput them in the routine.
insert image description here

awk '{sum=0;for(col=2;col<NF;col++) sum=sum+$col;allSum[$1]=sum}END{for(user in allSum) {total =allSum[user]} print total,NR,total/NR}' score.txtCalculate the sum of the scores of each user and store them in allSumthe array, then ENDoutput the total scores of all users in the routine, record the total number and the average score of all users.
insert image description here

awkThe script file can also be saved, and then the script file -fcan be called awk. ARGVis the command line array, ARGCand is the number of command line array elements.
scriptWithAwk.awkContents inside:

BEGIN{
    
    
   for(x=0;x<ARGC;x++){
    
    
      print ARGV[x]
   }
   print "ARGC number is " ARGC
}

awk -f scriptWithAwk.awk 11 13 15The output is:

awk
11
13
15
ARGC number is 4

awkis ARGV[0], 11is ARGV[1], 13is ARGV[2], 15is ARGV[3], ARGCthe value of is 4.
insert image description here

This article is a study note for Day 13 in August, and the content comes from "100 Lectures on Linux Practical Skills" by Geek Time .

Guess you like

Origin blog.csdn.net/qq_42108074/article/details/132258121