Pages

Saturday, December 12, 2015

array one liners


An array is a variable containing multiple values may be of same type or of different type.  There is no maximum limit to the size of an array, nor any requirement that member variables be indexed or assigned contiguously. Array index starts with zero.


1.       Declaring an Array and Assigning values

array_name[index]=value
where,
array_name – is any name for an array
index – can be any number or expression that must evaluate to a number greater than or equal to zero.

2.       Initializing an array during declaration

declare -a array_name=(element1 element2 element3)
Note: space is the default delimiter to separate elements of an array

3.       Print the Whole Bash Array

echo ${array_name[@]}

4.       Length of the Bash Array

echo ${#array_name[@]}

5.       Length of the nth Element in an Array

echo ${#array_name[n]}

6.       To extract 2 elements starting from the position 3 from an array called Unix.

echo ${array_name[@]:3:2}

7.       To extract only first four elements from an array element

echo ${array_name[2]:0:4}

8.       Search and Replace in an array elements

echo ${array_name[@]/string1/string2}

9.       Add an element to an existing Bash Array

array_name=('string1' 'string2' 'string3');
array_name=("${array_name[@]}" "string4" "string5")
echo ${array_name[@]}

10.   Remove an Element from an Array

array_name=('string1' 'string2' 'string3' 'string4' 'string5');
unset array_name[3]
echo ${array_name[3]}
echo ${array_name[@]}


array_name=('string1' 'string2' 'string3' 'string4' 'string5');
pos=2
array_name=(${array_name[@]:0:$pos} ${array_name[@]:$(($pos + 1))})
echo ${array_name[@]}

11.   Remove Bash Array Elements using Patterns

declare -a array_name=('Red string1' 'Blue string2' 'Green string3' 'White string4' 'Black string5');
declare -a patter=( ${array_name[@]/Red*/} )
echo ${patter[@]}

12.   Copying an Array

array_name1=('string1' 'string2' 'string3' 'string4' 'string5');
array_name2=("${array_name1[@]}")
echo ${array_name2[@]}

13.   Concatenation of two Bash Arrays

declare -a array_name1=('string1' 'string2' 'string3' 'string4' 'string5');
declare -a array_name2=('Red string1' 'Blue string2' 'Green string3' 'White string4' 'Black string5');

array=("${array_name1[@]}" "${array_name2[@]}")
echo ${array[@]}
echo ${#array[@]}

14.   Deleting an Entire Array

declare -a array_name1=('string1' 'string2' 'string3' 'string4' 'string5');
unset array_name
echo ${#UnixShell[@]}

15.   Load Content of a File into an Array

filecontent=( `cat "logfile" `)


No comments:

Post a Comment