Bash

Bash Split String

Bash Split String

In this topic, we've defined the way to split a string in bash shell scripting.

In some cases, we'd got to split the string data to perform some specific tasks. Most of the programming languages have built-in function 'split' to split any string data into various parts. However, bash doesn't contain such sort of built-in function. But we will use delimiters to separate any string data in bash scripting. The delimiter are often either one character or a string with multiple characters.

Check out the methods below to know the way to split string during a bash shell:

Split using $IFS variable

Following are the steps to separate a string in bash using $IFS:

$IFS may be a special internal variable that's wont to split a string into words. $IFS variable is named 'Internal Field Separator' which determines how Bash recognizes boundaries. $IFS is employed to assign the precise delimiter [ IFS='' ] for dividing the string. The white space may be a default value of $IFS. However, we will also use values like '\t', '\n', '-' etc. because the delimiter.

After assigning the delimiter, a string is often read by two options: '-r' and '-a'. i.e., read -ra ARR

Example1:

Splitting string by space.

#!/bin/bash  
#Example for bash split string by space  
  
read -p "Enter any string separated by space: " str  #reading string value  
  
IFS='' #setting space as delimiter  
read -ra ADDR <<<"$str" #reading str as an array as tokens separated by IFS  
  
for i in "${ADDR[@]}"; #accessing each element of array  
do  
echo "$i"  
done  

The output of the given code is :