Wednesday, January 11, 2017

grep vs awk - Part 2

In this article, we will see more awk alternatives for the frequently used grep commands. This is in continuation to the grep vs awk - Part 1. Let us consider a sample file as shown below:
$ cat file
Unix

Linux
Uniix
Solaris
AIX
ArchLinux
Ubuntu
1. Search for a pattern present in a variable
$ x="Linux"
$ grep "$x" file
Linux
The variable x contains the search pattern. Using grep, the variable can directly be used.
$ awk -v var="$x" '$0 ~ var' file
Linux
In awk, the variable cannot be used directly. It needs to be passed to awk from shell using the -v option. More about the variable passing to awk.

Wednesday, January 4, 2017

How to use arrays in ksh?

  Array, as in any programming language, is a collection of elements. These elements need not be of the same type. One important difference here is shells support only one-dimensional arrays.

1. Creating an array:
   Creating an array is pretty simple.
$ typeset -a arr
$ arr[0]=25
$ arr[1]=18
$ arr[2]="hello"
 Using the typeset command, we let the shell know that we are intending to use the variable arr to store a list of elements. The -a indicates arr as an indexed array. Then the elements are assigned one by one using their index positions. Array indexing always starts from 0.