Get the App
SLTechnology News&Howtos  ›  Servers  › 

Working principle and usage of Linux Awk Editing tool

Shulou Source: shulou.com Published: 2022-06-03 05:40:09 10月05日 Update

Brief introduction:

In Linux/UNIX system, awk is a powerful editing tool, which reads input text line by line, searches according to the specified matching pattern, formats and outputs or filters the content that meets the requirements, and can achieve quite complex text operations without interaction. It is widely used in Shell scripts to complete a variety of automatic configuration tasks.

working principle

Read text line by line, delimited by default with spaces as delimiters, save the delimited fields to built-in variables, and execute editing commands according to mode or condition

Common usage:

Single quotation marks and curly braces "{}" are used to set the processing action on the data. Awk can process the target file directly or through the "- f" read script.

Awk treats a line in a text file as a record and a part (column) of a line as a word (field) in a record. To manipulate these different fields, awk borrows a method similar to a location variable in shell, using $1, $2, $3... Sequentially represents different fields in a row (record). In addition, awk uses $0 to represent the entire line (record). Different fields are separated by specified characters. The default delimiter for awk is a space. Awk allows you to specify delimiters in the form of "- F delimiters" on the command line.

Command format

Awk [options] 'Mode or condition {Editing instructions}' File 1 File 2

Awk-f script file file 1 file 2

Special built-in variables

FS: specifies the field delimiter for each line of text, defaults to spaces or tab stops (tab key)

NF: the number of fields in the rows currently processed

NR: the line number of the currently processed row (ordinal)

$0: the entire line content of the currently processed line

$n: nth field of the currently processed row (nth column)

FILENAME: the name of the file being processed

RS: data records are separated. The default is\ n, that is, one record per behavior.

Relational operation symbol:

The specified action is performed only if the condition is true.

Greater than (>); less than (=); less than or equal to (

Tags: Fields output files processing content text delimiters beginnings conditions spaces differences variables commands patterns scripts lines between actions data formatting Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Linux Shulou Tech Info Apple MariaDB