Basic bash concepts, Part-9 (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
  9. Bash Part 8 Array

Basic bash concepts, Part-9 (Arrays)

In this part, we will remind you what we have discussed in previous post and array.
We studied following topics:
1. Declaring an Array and Assigning values

name[index]=value

2. Initializing an array during declaration

declare -a arrayname=(element1 element2 element3)

If the elements have the white space character, enclose it within a quote.

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

declare -a declares an array and all the elements in the parentheses are the elements of an array.

3. Print the Whole Bash Array

If the index number is @ or *, all members of an array are referenced. You can traverse through the array elements and print it, using looping statements in bash.

echo ${Unix[@]}

4. Length of the Bash Array
We can get the length of an array using the special parameter called $#.
${#arrayname[@]} gives you the length of the array.

echo ${#Unix[@]} #Number of elements in the array
echo ${#Unix}  #Number of characters in the first element of the array.

5. Length of the nth Element in an Array
${#arrayname[n]} should give the length of the nth element in an array.
6. Extraction by offset and length for an array
The following example shows the way to extract 2 elements starting from the position 3 from an array called Unix.

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

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

echo ${Unix[2]:0:4} #Ubuntu which is located at the second index of an array

8. Search and Replace in array elements

echo ${Unix[@]/Ubuntu/SCO Unix} #searches for 'Ubuntu' in an array & replace with ‘SCO Unix’.

9. Add an element in an existing Bash Array

Unix=("${Unix[@]}" "AIX" "HP-UX")

10. Remove an Element from an Array
unset is used to remove an element from an array.unset will have the same effect as assigning null to an element.

unset Unix[3]

11. Remove Bash Array Elements using Patterns

declare -a Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora');
declare -a patter=( ${Unix[@]/Red*/} )

12. Copying an Array

Linux=("${Unix[@]}") # linux is an array and unix is copied to it.

13. Concatenation of two Bash Arrays

Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Shell=('bash' 'csh' 'jsh' 'rsh' 'ksh' 'rc' 'tcsh');

UnixShell=("${Unix[@]}" "${Shell[@]}")

14. Deleting an Entire Array

unset UnixShell

15. Load Content of a File into an Array

filecontent=( `cat "logfile" `) #data is copied from logfile to array filecontent

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

Let’s understand the above synatxes using hackerrank questions.
1.Given a list of countries, each on a new line, your task is to read them into an array and then display the element indexed at 3. Note that indexing starts 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

The element at index of the array (one string).

Sample Input

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

Netherlands
Explanation

The element at index 3 in the list is Netherlands.

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

or

head -4| tail -1

or

array=(`cat`)
echo ${array[3]}


or

echo $(cat) | cut -f4 -d " "

Q2.Given a list of countries, each on a new line, your task is to read them into an array. Then, concatenate the array with itself (twice) – so that you have a total of three repetitions of the original array – and then display the entire concatenated array, with a space between each of the countries’ names.

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


or
declare -a p

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

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.