Show Menu
Cheatography

AWK - Part 3 Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Semicolon in AWK

As in many progra­mming languages like Java, the semicolon marks the end of one stateĆ¹ent and the begin of another one.
awke '{print $1 ; print $0}' awk.txt 
>>> AWK
>>> AWK is awesome
>>> Let
>>> Let learn AWK together
...

The special variable FS

We can put the field separator within an AWK program vy assigning a value to the special variable FS.
awk 'BEGIN {FS =","} {print $2}' 
Yellow­,Bl­ue,Red
>>> Blue

The special variable RS

By default, AWK treats each line of its input as a separate record. But what if the input line is not devided into lines ? Let take the file OneLin­e.txt as an example:
cat OneLin­e.txt 
AWK,is­,aw­eso­me!­Let­,le­arn­,AW­K!H­ell­o,AWK
In this file, fields are separated by comma and records are separated by exclam­ation point. Let see the following code which print the second field of each record.
awk 'BEGIN {RS="!";­FS=­"­,"} {print $2}' OneLin­e.txt 
>>> is
>>> learn
>>> AWK
 

OFS and ORS

AWK has also the output version of FS and RS which are respec­tively OFS and ORS. Let take an example using the file names.txt.
awk 'BEGIN {OFS=",­"­;OR­S="!­"} {print $1,$2}' names.txt 
>>> Albert­,Ei­nst­ein­!Ba­rak­,Ob­ama­!St­eve­,Jobs!
Note that the setting of OFS has no effect on the output of $0.

The special variable NR

NR is a special variable whose value is the record number or line number of the record that is currently being examined .
awk '{print NR,$0}' awk.txt 
>>> 1 AWK is awesome
>>> 2 Let learn AWK together
>>> 3 AWK is used for text processing
If we put two input files the result will be the concat­enation of the two files.

The special variable FNR

FNR is a special variable whose value is the record number of each file.
awk '{print FNR, $0}' names.txt awk.txt 
>>> 1 Albert Einstein
>>> 2 Barak Obama
>>> 3 Steve Jobs
>>> 1 AWK is awesome
>>> 2 Let learn AWK together
>>> 3 AWK is used for text processing
 

The special variable FILENAME

The special variable FILENAME print the name of a file.
awk '{print FILENA­ME,$0}' names.txt awk.txt 
>>> names.txt Albert Einshtein
>>> names.txt Barak Obama
>>> names.txt Steve Jobs
>>> awk.txt AWK is awesome
>>> awk.txt Let learn AWK together
>>> awk.txt AWK is used for text processing