Tip-Linux Awk

AWK Profile

Awk is abbreviated from the names of the developers – Aho, Weinberger, and Kernighan.

AWK functions

1.AWK Operations

  • (a) Scans a file line by line
  • (b) Splits each input line into fields
  • (c) Compares input line/fields to pattern
  • (d) Performs action(s) on matched lines

2.Useful for

  • (a) Transform data files
  • (b) Produce formatted reports

3.Programming Construct

  • (a) Format output lines
  • (b) Arithmetic and string operations
  • (c) Conditionals and loops

syntax

awk options 'selection _criteria {action }' input-file > output-file

Options

-f program-file : Reads the AWK program source from the file
program-file, instead of from the
first command line argument.
-F fs : Use fs for the input field separator

Examples

awk '/ manager / {print} ' employee.txt
used to filter out rows of matching manager, print out, where '' is divided into the inside and a corresponding selection Action, i.e. matching selection manager, a print entire row Action

awk '{Print $ 1, $}. 4' employee.txt
$ 1, $. 4 represent the first and fourth columns of that row, remember, where the number of columns starting from 1, not 0, and the default fields separator spaces and tab, wherein the whole line is expressed as $ 0

Built In Variables In Awk
built-in variables, there are about several
NR: indicates the number of lines per row, for example,

awk '{print NR, NF} ' employee.txt
indicates that the last line of each file print field

FS: FS command contains the field separator character which is used to divide fields on the input line. The default is “white space”, meaning space and tab characters. FS can be reassigned to another character (typically in BEGIN) to change the field separator.
RS: RS command stores the current record separator character. Since, by default, an input line is the input record, the default record separator character is a newline.

OFS: OFS command stores the output field separator, which separates the fields when Awk prints them. The default is a blank space. Whenever print has several parameters separated with commas, it will print the value of OFS in between each parameter.

ORS: ORS command stores the output record separator, which separates the output lines when Awk prints them. The default is a newline character. print automatically outputs the contents of ORS at the end of whatever it is given to print.

more examples

awk 'NR == 3, NR == 6 {print NR, $ 0}' employee.txt
print out the data lines 3 to 6, and each row strip line number

Reference

AWK command in Unix/Linux with examples

Guess you like

Origin blog.csdn.net/weixin_34248023/article/details/90973837