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:
- To declare an array of strings:
array_name=("string1" "string2" "string3" "string4")
- To declare an associative array of strings:
associative_array["key1"]="string1"
- To append an element to an array:
array_name+=("new element")
- To remove an element from an array:
unset cities[array_index]
- To sort an array alphabetically:
sorted_array=($(for i in "${array_name[@]}"; do echo $i; done | sort))
- 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"]}
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”
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
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 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[@]}
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.
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[@]}
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.
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
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.
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]}'
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’.
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
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.
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
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.
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
- How to Convert a Bash String to Int? [8 Methods]
- How to Format a String in Bash? [Methods, Examples]
- How to Convert Bash String to Uppercase? [7 Methods]
- How to Convert Bash String to Lowercase? [7 Methods]
- How to Replace String in Bash? [5 Methods]
- How to Trim String in Bash? [6 Methods]
- How to Truncate String in Bash? [5 Methods]
- How to Remove Character from String in Bash? [7+ Methods]
- How to Remove First Character From Bash String? [7 Methods]
- How to Remove Last Character from Bash String [6 Methods]
- How to Use String Functions in Bash? [Examples Included]
- How to Generate a Random String in Bash? [8 Methods]
- How to Use “Here String” in Bash? [Basic to Advance]
- Encode and Decode with “base64” in Bash [6 Examples]
- How to Use “eval” Command in Bash? [8 Practical Examples]
- How to Get the First Character from Bash String? [8 Methods]
<< Go Back to String Manipulation in Bash | Bash String | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners