1. Principle
awk, a line-of-text processing tool that processes data in a file on a row-by-line basis
Syntax: awk ' pattern + {action} '
Description
(1) The single quotation mark "is to separate from the shell command area;
(2) curly braces {} denote a grouping of commands;
(3) pattern is a filter that indicates that the line hitting pattern is handled by action;
(4) Action is the processing action;
(5) Use # as a comment;
The pattern parameter can be one of the egrep regular, and the regular use of the/pattern/
Example: Show lines 3rd through 5th in Hello.txt: Cat Hello.txt | awk ' nr==3, nr==5{print;} '
Example: Display hello.txt, regular matching Hello line: Cat Hello.txt | awk '/hello/'
Description
(1) Pattern and action can only be one, but not both;
(2) The default action is print;
Example: Display hello.txt with a length greater than 100 line number: Cat Hello.txt | awk ' Length ($) >80{print NR} '
#内置变量
FS delimiter, default is space
NR Current number of rows, starting from 1
NF Current record Field number
Current record
$1~ $n the nth field of the current record
Example: Show the first and last columns of line 3rd through 5th in Hello.txt: Cat Hello.txt | awk ' nr==3, Nr==5{print $, $NF} '
#内置函数
Gsub (r,s): use S instead of R in $ A
Index (S,T): Returns the first position of T in S
Length (s): s
Match (S,r): s matches R
Split (S,A,FS): divides s into sequence a on FS
SUBSTR (S,P): Returns the substring starting with P
#操作符
# #运算符
Similar to C, support + 、-、 *,/,%, + +, –, + =,-= and many other operations;
# #判断符
Similar to c, support = =,! =, >, = =, ~ (matching) and many other judgment operations;
#控制流程
# #BEGIN和END
The essence of begin and end is a pattern.
Begin to do some initialization work before the beginning of the AWK program;
End is used to do some finishing work before the awk program ends.
Example: awk ' begin {count=0;} {count+=length ($);} {print count;} End
# #流程控制语句
(1) if (condition) {}else{}
(2) while{}
(3) Do{}while (condition);
(4) for (Init;condition;step) {}
(5) Break/continue: If there is an end, it will perform the closing work in end
The Process Control statement usage is almost identical to C.
awk interaction with the shell
Use variables defined in the shell in Awk: use single quotes;
#!/bin/bash
str= "Hello"
echo | awk ' {
Print "' ${str} '";
}‘
Use shell commands in awk: Use double quotes, or system commands;
#!/bin/bash
echo Hello | awk ' {
Print $ | "Cat"
}‘
Linux record-awk syntax