Bash Split String



Bash Split String

In Bash scripting, splitting a string is useful for various tasks that require breaking down a string into parts based on a delimiter.


Syntax

IFS='delimiter'
read -ra array <<< "$string"

The basic syntax involves setting the Internal Field Separator (IFS) to the delimiter and using the read command with the -ra option to read the string into an array.


Example Bash Split String

Let's look at some examples of how to split a string in Bash:

1. Split a String by Spaces

This script splits the string stored in the variable str by spaces and prints each part.

#!/bin/bash

str="Hello World Bash Script"
IFS=' '
read -ra arr <<< "$str"
for element in "${arr[@]}"; do
    echo "$element"
done

In this script, the variable str is assigned the value 'Hello World Bash Script'. The Internal Field Separator (IFS) is set to a space. The read command splits the string into an array arr. The for loop iterates over each element in the array and prints it.

Split a string by spaces in Bash

2. Split a String by Commas

This script splits the string stored in the variable str by commas and prints each part.

#!/bin/bash

str="apple,banana,cherry"
IFS=','
read -ra arr <<< "$str"
for element in "${arr[@]}"; do
    echo "$element"
done

In this script, the variable str is assigned the value 'apple,banana,cherry'. The Internal Field Separator (IFS) is set to a comma. The read command splits the string into an array arr. The for loop iterates over each element in the array and prints it.

Split a string by commas in Bash

3. Split a String by a User-Specified Delimiter

This script prompts the user to enter a string and a delimiter, then splits the string by the specified delimiter and prints each part.

#!/bin/bash

read -p "Enter a string: " str
read -p "Enter the delimiter: " delimiter
IFS="$delimiter"
read -ra arr <<< "$str"
for element in "${arr[@]}"; do
    echo "$element"
done

In this script, the user is prompted to enter a string and a delimiter. The Internal Field Separator (IFS) is set to the user-specified delimiter. The read command splits the string into an array arr. The for loop iterates over each element in the array and prints it.

Split a string by a user-specified delimiter in Bash

Conclusion

Splitting a string in Bash is a fundamental task for breaking down a string into parts based on a delimiter in shell scripting. Understanding how to split strings can help you manage and manipulate strings effectively in your scripts.