data processing command
-F define column separator
awk 'condition type 1{action 1} condition type 2{action 2}...' filename
1. Read in the first line and divide the content by the delimiter (default space) , each field column can be accessed using $1, $2... .
Use $0 for the entire line
2. According to the limitation of "condition type", judge whether the following "action" needs to be performed;
3. Complete all actions and condition judgments;
4. If there are subsequent "line" data, repeat the above Steps 1~3 until all data are read.
Internal variables:
NF The total number of fields in each line
NR The current processing line
FS The current split character, the default space
FILENAME File name
BEGIN Execute before reading
END Execute after all the read data is processed
> last -n5 appoper pts/18 25.0.170.121 Thu Nov 2 15:17 still logged in appoper pts / 26 25.0.170.121 Thu Nov 2 15:13 - 15:19 (00:05) appoper pts / 18 25.0.170.107 Thu Nov 2 15:11 - 15:16 (00:05) appoper pts / 26 25.0.170.106 Thu Nov 2 15:10 - 15:11 (00:01) appoper pts / 18 25.0.170.121 Thu Nov 2 15:05 - 15:10 (00:05)
> last -n5|awk '{print $1"@"$3}' [email protected] [email protected] [email protected] [email protected] [email protected]
Split by ":", output the username whose uid is less than 10
> cat /etc/passwd |awk '{FS = ":"} $3 <10 {print $1}' root:x:0:0:root:/root:/bin/bash #The first line is not split, the following is processed by BEGIN bin daemon adm lp sync shutdown ....
Use the BEGIN keyword to execute the BEGIN statement first, and then read the content for processing.
> cat /etc/passwd |awk 'BEGIN{FS = ":"} $3 <10 {print $3 "\t" $1}' 0 root 1 bin 2 daemon 3 adm 4 lp 5 sync 6 shutdown .....
The content of the new text awk.txt:
a 10 20
b 23 34
c 12 13
count the sum of the second column, and execute after END processes all the read lines
> cat awk.txt|awk -F' ' 'BEGIN{total=0}{total=total+$2;print $2}END{print total}' 10 23 12 45
Statistics of current directory file size and
> ll|awk 'BEGIN{size=0}{size=size+$5}END{print "total size:"size}' total size:7467
Use printf [-v var] format [arguments] in combination with printf formatted output
\r carriage return
\n line feed
\t tab key
%ns n-length string
%ni n-length integer
%a.bf total length is a, decimal point float in the last b length format
> cat awk.txt |awk -F' ' '{printf "%4s%4i\t%4.2f\n",$1,$2,$3}' a 10 20.00 b 23 34.00 c 12 13.00