Sunday 17 January 2016

Bash shell scripting Array Operations

#!/bin/bash

#array declarations and its operations

arr[0]='apple'
arr[1]='orange'
arr[2]='lemon'
arr[3]='kiwi'

a[0]=1
a[1]=2
a[2]=3
a[3]=4

echo "${arr[@]}"

echo "${arr[0]}"
echo "${arr[1]}"
echo "${arr[2]}"
echo "${arr[3]}"

echo "Total length of array : ${#arr[@]}"

echo "size of arr[0] : ${#arr[0]}"


#using declare

declare -a city=('Chennai' 'Trichy' 'Madurai' 'Kovai')
city=("${city[@]}" 'Villupuram' 'Vellore')

echo "${city[@]}"

#offset

echo "${city[0]:0:3}"


echo "${city[@]}"

#search and replace

echo "${city[@]/Chennai/Madras}"

#remove
unset city[0]

echo "${city[@]}"

#remove with pattern
declare -a newcity=( ${city[@]/*ai/} )

echo "${newcity[@]}"

#copy entire array to newone

mycitylist=("${newcity[@]}")

echo -e "my final city list: \n ${mycitylist[@]} "

#join arrays
total=("${newcity[@]}"  "${arr[@]}" "${a[@]}" )

echo "${total[@]}"

#delete entire array
unset total
echo "${total[@]}"

No comments:

Post a Comment