Sunday 10 April 2022

AWK Essentials for DBAs and System Admins

  • The awk command is a very powerful Linux tool and programming language that allows users to process and manipulate data and produce formatted reports. The tool supports various operations for advanced text processing and facilitates expressing complex data selections. In this tutorial, you will learn what the awk command does and how to use it.

Scenario :

We need to print unique values from the 1st column. 

[oracle@rhel7 awk]$ awk -F, '{a[$1];}END{for (i in a)print i;}' a.txt

101

102

103

 

We have a file named a.txt

[oracle@rhel7 awk]$ cat a.txt

101,John,Smith

102,Karan,Dodwal

103,Oracle,Guru

# Here we want to check contents of the file

So just like cat, this awk command awk '{print;}' works :

 

[oracle@rhel7 awk]$  awk '{print;}'  a.txt

101,John,Smith

102,Karan,Dodwal

103,Oracle,Guru

 

[oracle@rhel7 awk]$ awk '{print $1}' a.txt

101,John,Smith

102,Karan,Dodwal

103,Oracle,Guru


Print 1st column with comma (,) as separator :


[oracle@rhel7 awk]$ awk -F "," '{print $1}' a.txt

101

102

103


Now lets print 3rd column :


[oracle@rhel7 awk]$ awk -F "," '{print $3}' a.txt

Smith

Dodwal

Guru


Print the lines which matches the pattern 


[oracle@rhel7 awk]$ awk '/Smith|Karan/' a.txt

101,John,Smith

102,Karan,Dodwal


Sum of all values in column 1 


[oracle@rhel7 awk]$ awk -F"," '{x+=$1}END{print x}' a.txt

306

## Printing the first row of a specific column outout from ps -ef | grep output

## First lets grep regular smon process

[oracle@rhel7 awk]$ ps -ef | grep smon

oracle     3742      1  0 16:07 ?        00:00:00 ora_smon_west

oracle     4999   3818  0 17:05 pts/2    00:00:00 grep --color=auto smon

# Now lets grep smon then second column and later first row that gets fetched from the second pipe

[oracle@rhel7 awk]$ ps -ef | grep smon | awk '{print $2}' | awk 'NR==1 {print $1}'

3742