Awk is also a streaming editor, which is more powerful than SED
1. Intercepting a paragraph in a document
awk -F ‘:‘ ‘{print $1}‘ /etc/passwd |head -2
-f Specifies the delimiter, without specifying a space or tab
Print Action for printing
$ $ for the first field, and $ $ for the second field, and so on, with the whole row marked
Then printing the entire document is
awk ‘{print $0}‘ /etc/passwd
Print also prints the custom content, enclosed in double quotation marks.
awk -F‘:‘ ‘{print $1"#"$2"#"$3"#"$4}‘ /etc/passwd |head -2
This means that the first four paragraphs are separated by a colon, and each segment is divided by the # number.
2. Match characters or strings
awk ‘/root/‘ /etc/passwd
Matches the row containing the root, which is similar to SED
Get a field to match
awk -F ‘:‘ ‘$1 ~/da/‘ /etc/passwd
Awk can also match multiple times, printing only the segments that are matched
awk -F ‘:‘ ‘/root/ {print $1 $3} /test/ {print $1 $3}‘ /etc/passwd
It means to find the line with the keyword root, test, and then print out the fields specified by these lines.
3. Conditional operators
Filtering based on logical judgments such as ==,<,<=,>,>=,!=
awk -F ‘:‘ ‘$3==0‘ /etc/passwd
awk-f ': ' $3>=500 '/etc/passwd so we've screened out the average user
The number following the logical symbol, if enclosed in double quotation marks, is handled by character
Give me one! Example of =
awk -F ‘:‘ ‘$7!="/sbin/nologin"‘ /etc/passwd
Of course, we can also work with fields
Awk-f ': ' $3<$4 '/etc/passwd
In addition, you can use the && | | means "and" and "or".
Awk-f ': ' $3<$4 && $3<10 '/etc/passwd
Awk-f ': ' $3>=500 | | $3<1 '/etc/passwd
4.awk built-in variables
NF: How many segments are separated by separators
NR: Number of rows
awk -F ‘:‘ ‘{print NF}‘ /etc/passwd |head -3
awk -F ‘:‘ ‘{print NR}‘ /etc/passwd |head -3
Use the line number as a criterion for the screening, you can also match a paragraph of characters
awk ' "NR" >20 '/etc/passwd
Awk-f ': ' nr>20 && $1~/test/'/etc/passwd
Mathematical operations in 5.awk
Change the content output of a field
awk -F ‘:‘ ‘$1="root"‘ /etc/passwd |head -3
Divide the first paragraph with a colon and replace it with Root
Awk can also perform mathematical operations on the values of individual segments:
awk -F ‘:‘ ‘{$7=$3+$4;print $0}‘ /etc/passwd |head -3
This statement indicates that the third and fourth paragraphs are summed and replaced by the seventh paragraph
You can also calculate a column's and
head -3 /etc/passwd |awk -F ‘:‘ ‘{(sum=sum+$3)}; END {print sum}‘
Here we have selected the first three lines of the file, the sum of the third column separated by a colon, sums is a variable can be arbitrarily taken, end is a keyword similar to the shell script done, in fact, the command is equivalent to a simple script with a loop statement
Use if in awk to determine if the for loop can be, give an if example
Awk-f ': ' {if ($3>=500) print $} '/etc/passwd
Linux Learning Summary (21) The regular three Musketeers of awk