Basic bash concepts, Part-8 (Arrays) with solved Hackerrank problems

Before this post, you have learned

  1. Basic bash hackerrank
  2. Shell beginner
  3. Bash II chapter
  4. Bash III chapter
  5. Bash IV chapter
  6. Bash V chapter
  7. Bash VI chapter
  8. Bash VII chapter

In this post we will discuss about array and operation.

What is array and how to use it in linux/unix

Array is an impressive display or range of a particular type of thing. or an ordered series or arrangement.

In Bash Linux

Array elements may be initialized with the variable[xx] notation. Alternatively, a script may introduce the entire array by an explicit declare -a variable statement. To dereference (retrieve the contents of) an array element, use curly bracket notation, that is, ${element[xx]}.
syntax

declare -a ARRAYNAME
ARRAY=(one two three)

echo ${ARRAY[*]}
one two three

echo $ARRAY[*]
one[*]

echo ${ARRAY[2]}
three

 ARRAY[3]=four

echo ${ARRAY[*]}
one two three four

unset command is used to free array

unset ARRAY[1]

Setting and displaying array value

Unix[0]='Debian'
Unix[1]='Red hat'
Unix[2]='Ubuntu'
Unix[3]='Suse'

echo ${Unix[1]}

 

declaration is like

declare -a Unix=('Debian' 'Red hat' 'Red hat' 'Suse' 'Fedora');

 

count element and size

echo ${#Unix[@]} #Number of elements in the array
echo ${#Unix} #Number of characters in the first element of the array.i.e Debian
echo ${#Unix[3]} # length of the element located at index 3 i.e Suse

 

if we want to display selected data

The following example shows the way to extract 2 elements starting from the position 3 from an array called Unix.

Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
echo ${Unix[@]:3:2}; #output will be: Suse Fedora

 

Extraction with offset and length, for a particular element of an array

To extract only first four elements from an array element . For example, Ubuntu which is located at the second index of an array, you can use offset and length for a particular element of an array.

Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
echo ${Unix[2]:0:4}; #Answer is: Ubun

 

Hackerrank problem on basic bash concepts, Part-8 (Arrays)

Q1.

Input Format

A list of country names. The only characters present in the country names will be upper or lower case characters and hyphens.

Output Format

Display the entire array of country names, with a space between each of them.

Sample Input

Namibia
Nauru
Nepal
Netherlands
NewZealand
Nicaragua
Niger
Nigeria
NorthKorea
Norway
Sample Output

Namibia Nauru Nepal Netherlands NewZealand Nicaragua Niger Nigeria NorthKorea Norway

Explanation

The entire array has been displayed.

while read line
do
    my_array=("${my_array[@]}" $line)
done
echo ${my_array[@]}


or


arr=($(cat))
arr=${arr[*]}
echo $arr


or

i=0
while read line
do
array[$i]=$line
((i+=1))
done

echo ${array[@]}


or

#! /bin/bash

i=1
while read line
do
    array[ $i ]="$line"
    (( i++ ))
done

printf "%s " "${array[@]}" | cut -d " " -f 1-${#array[@]}

Q2.

Given a list of countries, each on a new line, your task is to read them into an array. Then slice the array and display only the elements lying between positions 3 and , both inclusive. Indexing starts from from 0.

Input Format

A list of country names. The only characters present in the country names will be upper or lower case characters and hyphens.

Output Format

Display the sliced portion of the array of country names, with a space between each of them.

Sample Input

Namibia
Nauru
Nepal
Netherlands
NewZealand
Nicaragua
Niger
Nigeria
NorthKorea
Norway
Sample Output

Netherlands NewZealand Nicaragua Niger Nigeria
Explanation

We displayed the sliced portion of the array.

declare -a p

while read; do p+=($REPLY); done
echo "${p[@]:3:5}"

or


while read line
do
    my_array=("${my_array[@]}" $line)
done
echo "${my_array[@]:3:5}"

or


arr=$(cat)
echo ${arr[@]} | cut -d$' ' -f4-8


or

while read line
do
    my_array=("${my_array[@]}" $line)
done
echo ${my_array[@]:3:5}

or

tr '\n' ' ' | cut -d" " -f 4-8

Q3.
You are given a list of countries, each on a new line. Your task is to read them into an array and then filter out (remove) all the names containing the letter ‘a’ or ‘A’.

Input Format

The input format consists of a list of country names, each on a separate line. The only characters present in the country names will be upper or lower case characters and hyphens.

Output Format

From the given list, remove the names that contain ‘a’ or ‘A’ in them. If there are no names left after removing these characters, you should display a blank line.

Sample Input

Namibia
Nauru
Nepal
Netherlands
NewZealand
Nicaragua
Niger
Nigeria
NorthKorea
Norway
Sample Output

Niger

Explanation

Niger is the only name that does not contain an ‘a’ or ‘A’.

while read line
do
    array=("${array[@]}" $line)
done
echo ${array[@]/*[a|A]*/}

or
eof=false
index=0
while [ $eof != true ]; do
    read name || eof=true
    if [ $eof != true ]; then 
       index=$(($index+1)) 
       ar[index]=$name
    fi
done

declare -a ar2=(${ar[@]/*a*/})
declare -a ar3=(${ar2[@]/*A*/})
echo ${ar3[@]}

or

declare -a p

while read; do ! [[ "$REPLY" =~ a ]] && p+=($REPLY); done

echo "${p[@]}"


or
while read x; do
  has=`expr match "$x" '.*\([aA]\).*'`
  if [ "X$has" = "X" ]; then
    echo $x
  fi
done

or
while read line
do
    my_array=("${my_array[@]}" $line)
done
declare -a patter=( ${my_array[@]/*[aA]*/} )
echo ${patter[@]}

All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi

Leave a reply:

Your email address will not be published.