Awk: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 16: Line 16:
<tt>awk</tt> handles a stream of text as a sequence of '''records'''. The default record separator is the new line, so by default each line is handled as a record. Each record is broken up into a sequence of '''fields'''. By default, the field separator is white space. An <tt>awk</tt> program consists in '''condition-action''' statements, that are applied to the records, as they are fed into <tt>awk</tt>. Each record is scanned for the condition, which can be a pattern, among other things, and for each condition that matches, the associated action is executed.
<tt>awk</tt> handles a stream of text as a sequence of '''records'''. The default record separator is the new line, so by default each line is handled as a record. Each record is broken up into a sequence of '''fields'''. By default, the field separator is white space. An <tt>awk</tt> program consists in '''condition-action''' statements, that are applied to the records, as they are fed into <tt>awk</tt>. Each record is scanned for the condition, which can be a pattern, among other things, and for each condition that matches, the associated action is executed.


  awk '<''program''>' <''file''>
  awk '<''program''>' <''file-to-process''>


The '''program''' is a succession of:
The '''program''' is a succession of:
Line 27: Line 27:


For the above, the condition matches all records and the action prints out the first field.
For the above, the condition matches all records and the action prints out the first field.
The program can be specified in a separate text file, which is provided to <tt>awk</tt> by preceding the program file name with -f:
awk -f <''program-file-name''> <''file-to-process''>


=Referring Fields=
=Referring Fields=

Revision as of 22:43, 14 June 2018

External

Internal

Overview

awk handles a stream of text as a sequence of records. The default record separator is the new line, so by default each line is handled as a record. Each record is broken up into a sequence of fields. By default, the field separator is white space. An awk program consists in condition-action statements, that are applied to the records, as they are fed into awk. Each record is scanned for the condition, which can be a pattern, among other things, and for each condition that matches, the associated action is executed.

awk '<program>' <file-to-process>

The program is a succession of:

condition { action }

Example:

awk '{print $1}' ./sample.txt

For the above, the condition matches all records and the action prints out the first field.

The program can be specified in a separate text file, which is provided to awk by preceding the program file name with -f:

awk -f <program-file-name> <file-to-process>

Referring Fields

The fields are referred to with $<field-number> where field-number is 1-based: the first field in the record is $1.

Recipes