How to Manipulate Bash String Array [5 Ways]

String stores user and system information. An array of strings stores a collection of strings in an array. For manipulating the Bash string array, follow the syntaxes:

  1. To declare an array of strings: array_name=("string1" "string2" "string3" "string4")
  2. To declare an associative array of strings: associative_array["key1"]="string1"
  3. To append an element to an array: array_name+=("new element")
  4. To remove an element from an array: unset cities[array_index]
  5. To sort an array alphabetically: sorted_array=($(for i in "${array_name[@]}"; do echo $i; done | sort))
  6. To convert comma-separated string to array: array_name=($(echo $string_name | tr "," "\n")) Here, the comma will be replaced with a new line(“\n”) character.

In the following article, I will discuss each of the aforementioned methods to manipulate the Bash string array in detail. So let’s get started!

1. Declare an Array of Strings in Bash

In an index array, each array element is assigned across an index. To declare an index array of strings, follow the syntax:

array_name=("Tommy" "Huge" "Mike" "Wade")

It will declare an array of strings with four array elements.

On the other hand, the associative array uses key over number as indices. This type of array is useful for storing data in key-value pair format. Here, I will create an associative array and add two elements with keys:

#!/bin/bash

declare -A associative_array
associative_array["name"]="Susmit"
associative_array["country"]="Bangladesh"

echo ${associative_array["name"]}
EXPLANATION

The command declare -A associative_array declares an associative array. Then associative_array["name"]="Susmit" sets the value “Susmit” and “Bangladesh” to the key “name” and “country”. Finally, the echo command prints the value of associative_array having key “name”

Bash script has defined an associative array.

As in the above image, an associative array has been declared.

2. Loop Through String Array Indices

Looping through string array indices enables users to access the array elements and do the necessary operations. For accessing the array elements individually, for loop is the easiest approach. Here, I will loop through an array and print the elements on the terminal:

#!/bin/bash
array_name=("Tommy" "Huge" "Mike" "Wade")
for i in ${!array_name[@]}; do
  echo "element $i is ${array_name[$i]}"
done
EXPLANATION

Here, array_name=("Tommy" "Huge" "Mike" "Wade") defines the array_name array that possesses four elements. After that, for i in ${!array_name[@]}; do defines a for loop and iterates through each element of the array, and finally, the echo command prints the element on the terminal.

The for loop has accessed all the elements of string array.

The image shows that the loop has iterated through the array elements and printed them on the terminal.

3. Add and Remove Elements of the Array of String

To append a new array element to an existing array, use the array_name+=("new_element") syntax. And use the unset array_name[index] command to remove any element from an array. Here is a Bash script to do so:

#!/bin/bash

cities=("Brisbane" "Sidney" "Hobart")
echo “Intial array:”
echo ${cities[@]}
cities+=("Canberra")
echo “After Adding an Element to the array:”
echo ${cities[@]}
unset cities[1]
echo “After Removing an Element from the array:”
echo ${cities[@]}
EXPLANATION

Here,cities+=("Canberra") appends “Canberra” to the cities array. After that, unset cities[1] removes the element at index 1, which is the second element of the array.

Bash script has added an element to the array then deleted another element from the array.

In the image, the bash script has appended a new element to the array and removed another element from the array.

4. Sort Arrays of String

Sorting makes it easy for users to go through the strings inside an array and find the intended string. The sort command can print the contents of a file in a sorted manner. Here is a practical Bash script to do so:

#!/bin/bash
cities=("Brisbane" "Sidney" "Hobart")
sorted_cities=($(for i in "${cities[@]}"; do echo $i; done | sort))
echo “After Sorting the Elements of the array:”
echo ${sorted_cities[@]}
EXPLANATION

Here, sorted_cities=($(for i in "${cities[@]}"; do echo $i; done | sort)) defines a for loop that iterates over each element of the “cities” array and prints them on a new line. After that, the output of the for loop is piped to the sort command that sorts the words of that line alphabetically and stores the sorted words in the “sorted_cities” array.

Arrays elements are sorted.

The image shows a sorted string array.

5. Split String to Array

A string can be split by assigning the individual string words to a new array. For this, declare an empty array first, then iterate through each word of the main string using a for loop and append each of the words to the newly declared array. Here is the Bash script to do so:

#!/bin/bash
a=”Hello Welcome Here”
b=()
for i in $a; do
  b+=($i) ;
done
for c in ${b[@]}; do
  echo $c;
done
EXPLANATION

The for i in $a; do initiates a for loop that iterates over the words of string “a” individually by splitting them, considering “space” as a delimiter, and storing them to the iteration variable “i”. Then, it appends each word to the array “b”. Finally, the second for loop iterates over each element of array “b” and prints them on the terminal.

The bash script has converted the strings to array.

      I. Using “awk” Command

The awk command can split a string based on the specified delimited inside the split function. Here is a command to split a string based on space and print the 2nd element of the array:

echo "Hi Welcome Here" | awk '{split($0,a," "); print a[2]}'
EXPLANATION

The “Hi Welcome Here” string is piped to the awk command. The awk command splits the input string into fields based on the delimiter specified as “ ”(space) utilizing the split function and stores them as the elements of a. Finally, print a[2]}' command prints the second element of the array ‘a’.

The awk command has converted the string to an array.

    II. Using “read” Command

The read command with the -a option reads string input from the user as an array. To read a string from the user, use the syntax: read -a [array_name]. The -a option will split the input string, considering space(“ “) as an Internal Field Separator (IFS) character. Here is a bash script to read an array from the user and then print the element on the terminal:

#!/bin/bash

w=()
read -a w

for b in ${w[@]}; do echo $b ; done
EXPLANATION

read -a w reads input from the user and stores it in the array ‘w’. Here, the -a option specifies to read the input as an array. Then, for b in ${w[@]}; do echo $b ; done initiates a for loop that iterates over each element of w array and prints them individually after splitting them.

The read command with -a option has converted the string to array.

  III. Using “tr” Command

The tr (translate) command can replace the delimiter with a newline character. Thus, it can convert a string to an array. Here is a complete bash script to convert string to array:

#!/bin/bash

string="Dhaka,Chattogram,Sylhet"
array=($(echo $string | tr "," "\n"))
for element in "${array[@]}"; do
  echo "$element"
done
EXPLANATION

The script part, array=($(echo $string | tr "," "\n")) pipes the “Dhaka, Chattogram, Sylhet” string to the tr command that replaces each “,” with a newline character ‘\n’ and stores the elements to the array. Here, $( ) acts as a command substitution that captures the output of the tr command. Finally, the echo command inside a for loop prints each array element on the terminal.

The tr command has converted the string to array.

Some Tips While Manipulating String Arrays

While manipulating string arrays, be careful of the below facts:

Handling Spaces in Strings: In Bash, space is a delimiter. If space is present in the string, the bash will interpret it as separate elements.

Dealing with Empty or Undefined Elements: If you try to access an undefined array element, it will return an empty string.

Conclusion

This article will guide users in effectively handling and manipulating the bash string array to achieve the modified value of a string. It is a necessary tool for text processing and parsing important information.

People Also Ask

How do you store an array of strings in Bash?

To store an array of strings in Bash, use the syntax arr=(“Good” “Morning”). It will create an array named arr, having two strings, “Good” and “Morning” as elements.

How do you append a string to an array in Bash?

To append a string to an array in Bash, use the syntax array_name+=('appended string'). It will append the ‘appended string’ to the array_name array.

How do you convert a string to an array in Bash?

To convert a string to an array in Bash, use the syntax read -a array <<< “$string”. It will read a line from the standard input and split it into an array.

How do I find the length of an array in Bash?

To find the length of an array in Bash, use the syntax echo “${#array_name[@]}”. It will print the array length to the terminal.

How to create array in Bash?

To create an array in Bash, use the syntax array_name=(element1, element2, element3). It will create an array named array_name with three elements in it.

Related Articles


<< Go Back to String Manipulation in Bash | Bash String | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Susmit Das Gupta

Hello everyone. I am Susmit Das Gupta, currently working as a Linux Content Developer Executive at SOFTEKO. I am a Mechanical Engineering graduate from Bangladesh University of Engineering and Technology. Besides my routine works, I find interest in going through new things, exploring new places, and capturing landscapes. Read Full Bio

Leave a Comment