Linux /awk/ Usage
Linux awk Usage
Table of Contents
- 1. Sum a specific column:
- 2. Sum the columns of the lines with additional conditions(starting with 7):
- 3. Output the line whose value in the 3rd column is 1:
- 4. Output the line whose $1 < 80 and $2 > 20:
- 5. Count the lines starting with 7:
- 6. Output the line containg number 765
- 7. Output the line containing number 765 with the line number in front of that line:
- 8. Output the lines not containing number 765:
In this post, I am going to record the common patterns of using awk, the
amazing tool for processing file.
Assume I have a file (bb) with the following contents:
70 23 2
757 35 3
765 56 3
765 56 1
23 4
11 3
1 Sum a specific column:
awk ‘{sum += $1} END {print sum}‘ bb |
2 Sum the columns of the lines with additional conditions(starting with 7):
1: awk ‘/^7/ {print $2}‘ bb | awk ‘{sum += $1} END {print sum}‘
3 Output the line whose value in the 3rd column is 1:
1: awk ‘$3 == 1‘ bb
4 Output the line whose $1 < 80 and $2 > 20:
1: awk ‘{$1<80 && $2>20;print $3}‘ bb
5 Count the lines starting with 7:
1: awk ‘/^7/ {x++;} END {print x}‘ bb
6 Output the line containg number 765
1: awk ‘/765/‘ bb
7 Output the line containing number 765 with the line number in front of that line:
1: awk ‘/765/ {print NR":"$0}‘ bb
In the above command, the NR is the built-in variable that represents the line being processed, the $0 refers to the whole line.9
8 Output the lines not containing number 765:
1: awk ‘!/765/‘ bb
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。