Linux awk judgment and loop

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

judgment

awk '{if($2>=80){print $1;print $2}}' score.txtOutput the user name and score whose second field is greater than 80, but you can see that the user name and score are output in a new line.
insert image description here

awk 'BEGIN{OFS=" "}{if($2>=80){print $1,$2}}' score.txtOutput the grade and username on the same line.
insert image description here

cycle

whileThe cycle format is as follows:

while(条件表达式)
   awk语句集

doThe cycle format is as follows:

do{
    
    
   awk语句集
}while(条件表达式)

forThe cycle format is as follows:

for(初始值;判断条件;变量变化语句){
    
    
     awk语句集
}

awk '{sum=0; for(c=2;c<=NF;c++)sum=sum+$c;print sum}' score.txtThe total value of the corresponding scores for each row can be calculated.
insert image description here

awk '{sum=0; for(c=2;c<=NF;c++){sum=sum+$c;print sum}}' score.txt, the result of this calculation is wrong, because it outputs the data calculated for each row and column, and you can see that in the forfollowing {}, forthe loop can make the corresponding statement perform loop operations.
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/132255117