Awk Quick Start

Author Avatar
Young Hug Jul 11, 2021

This article is a quick start for beginner. The common usage is as following:

1
awk <Action> <File Name>

awk will use space and tab to split every line into multiple setions using $1,$2 to represent.

Variable

we use $+Number variable to represent the sections of a line. The normal variable is as following:
NF: the number of the sections in current line.
$NF: the last section of current line
$(NF-1): the last two section of current line

Built-in variable

  • FILENAME File name
  • FS Field spilitor
  • RS Row spilitor
  • OPS Output spilitor
  • ORS Output record spilitor
  • OFMT Ouput format of numbers

Built-in function

  • tolower()
  • toupper()
  • length()
  • substr()
  • sin()
  • cos()
  • sqrt()
  • rand()

Condition

Condition is for juding the output. The normal format is as following:
awk '<condition> <action>' <FileName>

1
2
awk -F ':' '/usr/' demo.txt
awk -F ':' 'NR %2 ==1 {print $1}' demo.txt

IF expression

IF expression is a kind of condition. The example is as following:

1
2
awk -F ':' '{if ($1 >"m") print $1}' demo.txt
awk -F ':' '{if ($1 >"m") print $1; else print "==="}' demo.txt

This blog is under a CC BY-NC-SA 3.0 Unported License
Link to this article: https://younggod.netlify.app/2021/07/11/Knowledge/Awk/awk-quickstart/