Stay at Home!! Be Safe!! Take Care!!

Thanks all my viewers for your support, I am an Oracle Ace now. For Any queries, please mail us at support@funoracleapps.com

LINUX AWK Tutorial Series | Chapter 8

No comments

LINUX AWK Tutorial Series | Chapter 8

How are you liking the series, please do provide your feedback?

In this chapter, I am going to discuss, arrays in AWK.

Array

It is a collection of related elements. It avoids using multiple variables and use one array in place of it. It can store both numbers and strings.
Array element values are mapped as index and value mapping.
No array declaration is required. No initialization of the number of elements stored in an array is required.

The syntax for assigning array is 

array_name[index]=value

An index can be a number or string. The string has to be enclosed within double quotes("")

Sample file:

[himanshu@oel7 AWK]$ cat array_file
BEGIN
{
month[1]="January"
month["first"]="January"
month[2]="Febuary"
month["second"]="Febuary"
month[12]="December"
month["twelth"]="December"
}

In array, index need not be defined in sequence. Any new index in the array can be added.

If we need to access an array element then use the following

arrayname[index]


Example 1:

Printing a simple array



I am just printing the array value. I have created and used awk scripts.

Now let's say I want to check whether an index has a value defined or not.

Here we will use In operator in an array.

Example 2:



I have mentioned if condition which will match if an index is present in an array. If the index is not present then it will not print any thing.

Example 3:

Check for the value on an index is null or not.



I am matching value as month[11] != "" for  not null.



As index 11 is not defined, it will not print anything. But there is a problem with this method, It will actually create an index 11 with a null value if we are comparing in the above-given method.

That's it preferred to use In operator for checking.

See and understand what was done here.

[himanshu@oel7 AWK]$ cat array_file
BEGIN{
month[1]="January";
month["first"]="January";
month[2]="Febuary";
month["second"]="Febuary";
month[12]="December";
month["twelth"]="December";
print month[12] 
if (2 in month)
print "Index 2 has been defined"
if (12 in month)
print "Index 12 has been defined"
if (month[11] != "" )
print "Index 11 is not null"
if (11  in month)
print "Index 11 is null"
}
[himanshu@oel7 AWK]$ awk -f array_file
December
Index 2 has been defined
Index 12 has been defined
Index 11 is null



More chapters to continue.

If you like please follow and comment

No comments :

Post a Comment