Linux AWK Command Tutorial and Examples-DecodingDevOps

Linux AWK Command Tutorial and Examples

Linux AWK Command

linux AWK command provides a scripting language for text processing. linux AWK command is simple yet powerful enough to perform text processing based on patterns and rules we specify. It works by scanning the file line by line and performing actions that we have specified when the rules match. in this Linux awk command tutorial i am going to explain most useful examples of awk command.

Capablities of AWK

  • Variables
  • Arithmatic Operations
  • Loops and Control Statements
  • Output Formatting
  • Pattern matching
  • Report Generation

linux awk command examples

Here are some example how you can use linux AWK command

$ cat sample.txt

Bill    Microsoft
Steve   Apple 
Elon    Tesla
Jeff    Amazon

Print the columns with linux AWK command

{print $0} will print all the columns

$ awk '{print $0}' sample.txt

Bill    Microsoft
Steve   Apple
Elon    Tesla
Jeff    Amazon

{print $1} will print only the first column

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

Bill
Steve
Elon
Jeff

{print $2} will print only the second column

$ awk '{print $2}' sample.txt

Microsoft
Apple
Tesla
Amazon

Match the Pattern with Linux AWK command

By keeping any pattern in ‘/’ we can match that pattern and it will only print the lines containing the pattern

$ awk '/Bill/ {print $0}' sample.txt

Bill    Microsoft

Count the rows with linux awk command

NR will count the number of rows in the document.

$ awk '{print NR, $0}' sample.txt

1 Bill    Microsoft
2 Steve   Apple 
3 Elon    Tesla
4 Jeff    Amazon

Count the fields with linux awk command

NF will count the number of fields in the record.

$ awk '{print NF, $0}' sample.txt 

2 Bill    Microsoft
2 Steve   Apple 
2 Elon    Tesla
2 Jeff    Amazon

Seprate Records with linux awk command

We can use ORS (Output Record Seprator) to seprate records using desired character with awk command.

$ awk 'BEGIN  {ORS=":"} {print $0}' sample.txt 
 
Bill    Microsoft:Steve Apple:Elon      Tesla:Jeff      Amazon:

We can use OFS (Output Field Seprator) to seprate fields using the desired character.

$ awk 'BEGIN  {OFS="="} {print $1, $2}' sample.txt

Bill=Microsoft
Steve=Apple
Elon=Tesla
Jeff=Amazon

Count The Records with linux awk command

We can count the number of records using NR in awk command

$ awk 'END {print NR}' sample.txt

4

Use Loops in Linux AWK command

We can use for loop in linux awk command.

$ awk 'BEGIN {for(i=1;i<=5;i++) print "Hello ",i }'

Hello  1
Hello  2
Hello  3
Hello  4
Hello  5

Use If statement in linux awk command

We can use control statements like 'if statement' in awk command as below.

$ awk '{if($2=="Apple") print $0}' sample.txt

Steve   Apple