Tuesday, February 10, 2009

arrays in bash shell - Part 2

In my previous post, I explained basic arrays usage in bash shell. Now, I'll show more advanced topics with bash arrays.Let's create a simple array called myarray.

# myarray=(first second third fourth)

Now, assume that you want to learn string length of second element of myarray.

# echo ${#myarray[1]}

this will 6 for string "second".Note here that, array indexes are starting from 0. So, 1 index numbers actually is 2nd element of the array.

Here is another example, this one will skip first element of the array and gives rest of the array.So,following will do the trick.

# echo ${myarray[@]:1}

going further with this example.Let's say we want to skip first element and need no more than 2 elements in the array

# echo ${myarray[@]:1:2}

result will be "second third".

Search and Replace

You can search and replace patterns or characters in given array or any array element.
Here is two examples, first one will search all elements of array for character "r" and replace all characters with "R". Second example, will do the same thing but only for 2nd element of the given array.

# echo ${myarray[@]/r/R}

# echo ${myarray[1]/r/R}

Above examples, will only replaces first occurrences, for replacing whole occurrences use double slashes.For example,

# echo ${myarray[1]//r/R}


Deleting and Adding Array Elements

Deleting any element is very simple. You just have to use "unset" command and give index number of array element.Following, will delete 2nd element of the array.

# unset myarray[1]

now our example array will contain "first third fourth" elements.Deleting the whole array is very simple.Don't pass the index number to unset.

# unset myarray

Now, Let's a new entry to our array.

# myarray=("${myarray[@]}" "fifth_element")

1 comment:

Anonymous said...

Lets say I have the following array:

# myarray=(bigcar smallcar car truck)

Now I only want to delete elements that are exactly "car". Is there a way to do that using the following syntax:

# ${myarray[@]/car/}

without modifying the other elements of the array?