Bash Split String Examples

29/12/2020
We need to split the string data for various purposes in the programming. Many programming languages have a built-in function named ‘split’ for divide any string data into multiple parts. But there is no built-in function in bash for dividing the string. Normally, single or multiple delimiters are used to split any string data. How you can split the string in bash is shown in this tutorial by using different examples.

Using $IFS variable

The special shell variable $IFS is used in bash for splitting a string into words. $IFS variable is called Internal Field Separator (IFS) that is used to assign the specific delimiter for dividing the string. Word boundaries are identified in bash by $IFS. White space is the default delimiter value for this variable. Any other value like ‘t’, ‘n’, ‘-‘ etc. Can be used as the delimiter. After assigning the value into $IFS variable, the string value can be read by two options. These are ‘-r’ and ‘-a’. The option, ‘-r’ is used to read backslash() as a character rather than escape character and ‘-a’ option is used to store the split-ted words into an array variable. The string can be split-ted without using $IFS variable in bash. Different ways to split string data (with $IFS or without $IFS) are shown in the following examples.

Example-1: Split string based on

The string value is divided by white space by default. Create a file named ‘split1.sh’ and add the following code. Here, $text variable is used to assign a string value. The shell variable, $IFS is used to assign the character that will be used for dividing the string data. Space is used in this script as the separator. ‘-a’ option is used with reading command to store the split-ted data into an array variable named $strarr. ‘for’ loop is used to read each element of the array, $strarr.

split1.sh

#!/bin/bash

#Define the string value
text="Welcome to LinuxHint"

# Set space as the delimiter
IFS=‘ ‘

#Read the split words into an array based on space delimiter
read -a strarr <<< "$text"

#Count the total words
echo "There are ${#strarr[*]} words in the text."

# Print each value of the array by using the loop
for val in "${strarr[@]}";
do
  printf "$valn"
done

Output:

Run the script.

$ bash split1.sh

The following output will appear after running the script.

Example-2: Split string based on a particular character

Any specific character can be used as the separator for dividing the string value. Create a file named split2.sh and add the following code. Here, book name, author name and price value are taken by adding comma(,) as an input string. Next, the string value is split-ted and stored in an array based the value of the shell variable, $IFS. Each value of the array elements is printed by the index value.

split2.sh

#!/bin/bash

#Read the string value
echo "Enter book name, author name and price by separating comma. "
read text

# Set comma as delimiter
IFS=‘,’

#Read the split words into an array based on comma delimiter
read -a strarr <<< "$text"

#Print the splitted words
echo "Book Name : $strarr[0] "
echo "Author Name : #strarr[1] "
echo "Price : $strarr[2]"

Output:

Run the script.

$ bash split2.sh

The following output will appear after running the script.

Example-3: Split the string without $IFS variable

This example shows how the string value can be divided without using $IFS in bash. Create a file named ‘split3.sh’ and add the following code. According to the script, a text value with the colon(:) has to take as input for splitting. Here, ‘readarray’ command with -d option is used to split the string data. ‘-d’ option is used to define the separator character in the command like $IFS. Next, ‘for’ loop is used to print the array elements.

split3.sh

#!/bin/bash

#Read the main string
echo "Enter the string with colon(:) to split"
read mainstr

#Split the string based on the delimiter, ‘:’
readarray -d : -t strarr <<< "$mainstr"
printf "n"

# Print each value of the array by using loop
for (( n=0; n < ${#strarr[*]}; n++))
do
  echo "${strarr[n]}"
done

Output:

Run the script.

$ bash split3.sh

The following output will appear after running the script.

Example-4: Split the string with a multi-character  delimiter

The string value is split-ted by a single character delimiter in all previous examples. How you can split the string by using multi-character delimiter is shown in this example. Create a file named ‘split4.sh’ and add the following code. Here, $text variable is used to store a  string data. $delimiter variable is used to assign a multi-character data that is used as the delimiter in the next statements. $myarray variable is used to store each split-ted data as an array element. Finally, all split-ted data are printed by using ‘for’ loop.

split4.sh

#!/bin/bash

#Define the string to split
text="learnHTMLlearnPHPlearnMySQLlearnJavascript"

#Define multi-character delimiter
delimiter="learn"
#Concatenate the delimiter with the main string
string=$text$delimiter

#Split the text based on the delimiter
myarray=()
while [[ $string ]]; do
  myarray+=( "${string%%"$delimiter"*}" )
  string=${string#*"$delimiter"}
done

#Print the words after the split
for value in ${myarray[@]}
do
  echo -n "$value "
done
printf "n"

Output:

Run the script.

$ bash split4.sh

The following output will appear after running the script.

Conclusion:

The string data need to split for different programming purposes. Various ways of splitting string data in bash are shown in this tutorial. Hope, after practicing the above examples, the readers will be able to split any string data based on their requirement.

For more information watch the video!

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

Bash Arithmetic Operations

Doing arithmetic operations in bash is not similar to other standard programming languages. One of the limitations of bash...
29/12/2020

Bash Getopts

Sometimes we need to read command line arguments and options in bash scripts. Command line arguments can be easily read...
29/12/2020

Bash Split String Examples

We need to split the string data for various purposes in the programming. Many programming languages have a built-in function...
29/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Tìm Hiểu Về Thuê Proxy US – Lợi Ích và Cách Sử Dụng Hiệu Quả
11/12/2024

Mua Proxy V6 Nuôi Facebook Spam Hiệu Quả Tại Onetcomvn
03/06/2024

Hướng dẫn cách sử dụng ProxyDroid để duyệt web ẩn danh
03/06/2024

Mua proxy Onet uy tín tại Onet.com.vn
03/06/2024

Thuê mua IPv4 giá rẻ, tốc độ nhanh, uy tín #1
28/05/2024