Designed for data extraction and reporting.
awk
is its own programming language itself and contains a lot of really good tools, enables a programmer to write tiny but effective programs in the form of statements that define text patterns that are to be searched for in each line of a document and the action that is to be taken when a match is found within a line.
Reference from GeeksforGeeks awk in 20 mins WHAT CAN WE DO WITH AWK ?
-
AWK Operations: (a) Scans a file line by line (b) Splits each input line into fields © Compares input line/fields to pattern (d) Performs action(s) on matched lines
-
Useful For: (a) Transform data files (b) Produce formatted reports
-
Programming Constructs: (a) Format output lines (b) Arithmetic and string operations © Conditionals and loops
日期记录的部分主要平时遇到的零散总结: ################################################################ # Date Description # 09/11/2019 skip first line # 02/28/2019 print last column # 02/26/2019 awk remote execution # ################################################################
02/26/2019
When use awk
in script, may suffer shell unexpected expanding:
1 | ssh -o StrictHostKeyChecking=no sshrm1 "ifconfig eth0 | grep \"inet\" | awk '{print $2}'" |
Above will not get right data, instead preceding \
before $
1 | ssh -o StrictHostKeyChecking=no sshrm1 "ifconfig eth0 | grep \"inet\" | awk '{print \$2}'" |
Another method is awk
the return value from ssh
rather than wrap it in ssh
command.
02/28/2019
Print last column separated by space:
1 | ## NF: count of fields of a line |
09/11/2019
Skip the first line:
1 | ## NR: current count of lines |
You can use NR>=2
, NR<5
, NR==3
, etc to limit the range.
Quick Start
1 | ## check version |
awk
has BEGIN and END block, between is the body:
1 | ## BEGIN and END run only once |
We can also put the awk option into awk script:
1 | awk -f file.awk /etc/passwd |
file.awk
content:
1 | ## FS is used to specify delimiter to parse line, by default awk use space |
Let’s see more examples, actually sed may perform the same task but awk is more readable.
1 | ## set "," as delimiter, $1 to uppercase, $2 to lowercase |
lastlog.awk file to show non-root user login statistics
1 | ## exclude if match these: |