In some cases, when working with a bash script, there arises a need to separate strings based on a delimiter and extract multiple strings for further processing or storage in variables.
This tutorial guides you through string splitting with examples in bash shell programming.
This article covers three methods.
- Split a string using awk command
- Use IFS variable
- Parameter Expansion with for loop
Split a string using the awk command in a bash shell script
The awk
command, a Linux utility compatible with all bash and shell distributions, is used to split a string based on a specified delimiter
.
The input is provided using the pipe (|) symbol, and the example below demonstrates splitting a string containing colons (:
)
str="abc:def:ghi"
echo "$str" | awk -F':' '{print $1,$2,$3}'
output:
abc def ghi
split using IFS variable
Here, the input string consists of elements separated by hyphens
. The shell variable IFS
(Internal Field Separator) is set to a hyphen, and the string is iterated using a for loop.
Each element is printed after removing the hyphen.
input="one-two-three"
IFS='-' array=($input)
for element in "${array[@]}";
do
echo $element;
done
Output
output:
one
two
three
Use Parameter expansion and loop
Parameter expansion is employed to change the variable value based on specified options. In this case, a string variable is converted to an array. The array is then iterated using a for loop syntax, printing each element to the console:
msg="Welcome to my site."
array=($msg)
for item in "${array[@]}"; do
echo "$item"
done
Different ways to handle string manipulations, allowing you to choose the method that suits your needs.