Awk Command

Awk is a powerful tool in Unix. Awk is an excellent tool for processing the files which have data arranged in rows and columns format. It is a good filter and report writer.

 

• Write a command to print the squares of numbers from 1 to 10 using awk command?

awk 'BEGIN { for(i=1;i<=10;i++) {print "square of",i,"is",i*i;}}'

 

[root@sys2 ~]# awk 'BEGIN { for(i=1;i<=10;i++) {print "square of",i,"is",i*i;}}'

 

square of 1  is 1
square of 2  is 4
square of 3  is 9
square of 4  is 16
square of 5  is 25
square of 6  is 36
square of 7  is 49
square of 8  is 64
square of 9  is 81
square of 10 is 100

 

Write a command to find the sum of bytes (size of file) of all files in a directory?

ls -l | awk 'BEGIN {sum=0} {sum = sum + $5} END {print sum}'

 

[root@sys2 ~]# pwd /root
[root@sys2 ~]# ls -l | awk 'BEGIN {sum=0} {sum = sum + $5} END {print sum}'
32879567

 

• In the text file, some lines are delimited by colon and some are delimited by space. Write a command to print the third field of each line.

awk '{ if( $0 ~ /:/ ) { FS=":"; } else { FS =" "; } print $3 }' filename

 

[root@sys2 ~]# awk '{ if( $0 ~ /:/ ) { FS=":"; } else { FS =" "; } print $3 }' /etc/passwd
1
2
3
4
5
6
7
8
10
11
12
13
14

 

Write a command to print the line number before each line?

awk '{print NR, $0}' filename'

 

[root@sys2 ~]# awk '{print NR, $0}' /etc/passwd
1  root:x:0:0:root:/root:/bin/bash
2  bin:x:1:1:bin:/bin:/sbin/nologin
3  daemon:x:2:2:daemon:/sbin:/sbin/nologin
4  adm:x:3:4:adm:/var/adm:/sbin/nologin
5  lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
6  sync:x:5:0:sync:/sbin:/bin/sync
7  shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
8  halt:x:7:0:halt:/sbin:/sbin/halt
9  mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
10 uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin

 

• Write a command to print the second and third line of a file without using NR?

awk 'BEGIN {RS="";FS="\n"} {print $2,$3}' filename'

 

[root@sys2 ~]# awk 'BEGIN {RS="";FS="\n"} {print $2,$3}' /etc/passwd
bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin

 

• Write a command to find the total number of lines in a file without using NR?

awk 'BEGIN {sum=0} {sum=sum+1} END {print sum}' filename'

 

[root@sys2 ~]# awk 'BEGIN {sum=0} {sum=sum+1} END {print sum}' /etc//passwd
39

 

Another way to print the number of lines is by using the NR. The command is

[root@sys2 ~]# awk 'END{print NR}' /etc/passwd
39