How to use awk in built functions for string and I/O manipulation ?

In this article I am going to demonstrate the usage of awk in built functions.

Built in functions for string manipulation:

1) length function : This function is used to calculate the length of string.

In below one liner I am listing the files present in directory after that I am printing only those files whose file name is greater than 10.

[root@Node2 awk]# ls -lrt | awk ‘{if (length($9) > 10) {print}}’
-rwxr-xr-x. 1 root root 113 Oct 2 00:15 fieldwidth.sh
-rwxr-xr-x. 1 root root 147 Oct 2 00:33 lengthawk.sh

2) index function : This will search for the first occurrence of string.

In below case I am checking for the sub directories present in current directory. I am comparing the first parameter of permission with d, if its d, then it is directory and it will get print.

[root@Node2 awk]# ls -lrt | awk ‘{if (index($1,”d”)) {print}}’
drwxr-xr-x. 2 root root 4096 Oct 2 00:48 check

3) substr function : This returns the substing of string depending upon the values given.

In this script I am extracting the first name of domain from whole name using substr function.

Input file

[root@Node2 awk]# cat data2
random.com
vicky.co.in
simon.uk.com

Script 

[root@Node2 awk]# cat substrawk1.sh
#!/bin/awk -f
{
if ((x=index($1,”.”)) > 0) {
domainname = substr($1,1,x-1);
domain = substr($1,x+1,length($1));
printf (“domainname = %s, domain = %s \n”, domainname, domain);
}
}

Output after running the script on input file.

[root@Node2 awk]# ./substrawk1.sh data2
domainname = random, domain = com
domainname = vicky, domain = co.in
domainname = simon, domain = uk.com

4) split function It will split the input into array we need to specify the separator.

Here I am splitting the time in date command by giving the : as separator.

[root@Node2 ~]# date
Thu Oct 9 22:38:28 IST 2014

[root@Node2 ~]# date | awk ‘{split($4,a,”:”); print a[2]}’
38

Built in function for Input and output.

1) system : It is used to run the system command using awk.

Below command will help to show the status of user account whether its locked or not.

 [root@Node2 ~]# cat /etc/passwd | awk -F: ‘{system(“passwd -S ” $1)}’

2) getline : it is used to read the input in awk.

Below simple program will read the the input from stdin and output that.

#/bin/awk
BEGIN { printf “Enter your name: ”
getline < “-”
print
}

Output 

[root@Node2 ~]# awk -f awk1.sh
Enter your name: James
James

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s