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
awk '{sum=0;for(col=2;col<NF;col++) sum=sum+$col;allSum[$1]=sum}END{print allSum["zhaoy"]}' score.txt
zhaoy
The total score can be seen 366
. NF
Yes 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" .
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.txt
Calculate the sum of the user's grades, store them allSum
in the array, and END
output them in the routine.
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.txt
Calculate the sum of the scores of each user and store them in allSum
the array, then END
output the total scores of all users in the routine, record the total number and the average score of all users.
awk
The script file can also be saved, and then the script file -f
can be called awk
. ARGV
is the command line array, ARGC
and is the number of command line array elements.
scriptWithAwk.awk
Contents inside:
BEGIN{
for(x=0;x<ARGC;x++){
print ARGV[x]
}
print "ARGC number is " ARGC
}
awk -f scriptWithAwk.awk 11 13 15
The output is:
awk
11
13
15
ARGC number is 4
awk
is ARGV[0]
, 11
is ARGV[1]
, 13
is ARGV[2]
, 15
is ARGV[3]
, ARGC
the value of is 4
.
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 .