Pattern of 1.AWK
BEGIN
END
expression Example: nf>10 or/^a/
/regular expression/?
You can use a/^a/like this.
Another way of writing $ ~/^a///Field match
Between expressions you can use && | | !?: Operators do Boolean operations (which can be regular expressions, of course)
expression, expression table, start and end examples: nf==5,nf==10
Example 1:CAT/ETC/PASSWD |awk-f ":" ' nr==5,nr==10{print nr,$1} '//Show only passwd lines for 第5-10 files, and define fields delimited by: No.
5 Sync
6 games
7 Mans
8 LP
9 Mail
Ten News
Knowledge Point: 1.-f parameter. 2.expression, expression usage.
Action of 2.AWK
A perfect programming language? Support variable assignment, array, judgment, loop, custom function
It's very handy. predefined variables and functions
The most common use is the print function.
Fields are valued at $, $, $ ... $NF
$ A is all the lines of the file
Note: awk's definition variable does not have to be the $ sign at the beginning, and the $ symbol is the Fetch field value.
Example 2:awk ' begin{rs= ' [^0-9a-za-z] '}; {count[$0]++}; End{for (i in count) print I,count[i]} ' <1.txt
Iwant 1
Chinawelcome 1
Ilove 1
to 7
China 4
Love 4
Changsha 5
I 4
Beijing 2
Welcome 5
You 5
Note: The statement function: Extract each word of the file out of a separate row, and count the number of occurrences of the word.
Knowledge Points: 1. Begin,end blocks are written and used (enclosed in {}; to separate). 2. Separator RS and FS difference (RS: Encounter RS is another line). 3. Use of arrays. 4.for Loop. 5. File redirection input
Example 3 extending the above example (sorting and writing a new file)
awk ' begin{rs= ' [^0-9a-za-z] '}; {count[$0]++}; End{for (i in count) print I,count[i] | "Sort-r-k2-o 3.txt"} ' <1.txt
Knowledge Points: 1.print usage. Print ... | Command: Commands and outputs the output of print as command input. Note that the entire command includes all parts of the parameter in double quotes.
2. Sort usage. The-o parameter writes the sorted result to the file, and this redirect grammar is completed.
3. Usage of Getline
Example: Merging files together.
VI Join.awk
#!/usr/bin/awk-f
{
Getline Sl<argv[2]
Print $ SL
}
Execution: awk-f Join.awk file1 file2
Linux Shell Learning awk---beginner's notes