- Bash Split String Examples
- Using $IFS variable
- Example-1: Split string based on space
- Example-2: Split string based on a particular character
- Example-3: Split the string without $IFS variable
- Example-4: Split the string with a multi-character delimiter
- Conclusion:
- About the author
- Fahmida Yesmin
- Bash Split String
- Bash Split String
- Split String with single character delimiter(s) in Bash using IFS
- Example 1: Bash Split String by Space
- Example 2: Bash Split String by Symbol
- Split String with multiple character delimiter
- Example 3: Split String with another string as delimiter idiomatic expressions
- Example 4: Bash Split a String with multiple character delimiter
- Conclusion
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 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 space
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.
#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
#Count the total words
echo «There are $ words in the text.»
# Print each value of the array by using the loop
for val in » $ » ;
do
printf » $val \n »
done
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.
#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
#Print the splitted words
echo «Book Name : $ »
echo «Author Name : $ »
echo «Price : $ «
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.
#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 printf » \n «
# Print each value of the array by using loop
for ( ( n = 0 ; n < $; n++ ) )
do
echo » $ »
done
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.
#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 = $
done
#Print the words after the split
for value in $
do
echo -n » $value »
done
printf » \n «
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!
About the author
Fahmida Yesmin
I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.
Bash Split String
Bash Split String – Often when working with string literals or message streams, we come across a necessity to split a string into tokens using a delimiter. The delimiter could be a single character or a string with multiple characters. In this tutorial, we shall learn how to split a string in bash shell scripting with a delimiter of single and multiple character lengths.
Bash Split String
Split String with single character delimiter(s) in Bash using IFS
To split a string in bash using IFS, follow the below steps:
Step 1: Set IFS to the delimiter you would want. IFS=» IFS is an internal variable that determines how Bash recognizes word boundaries. The default value of IFS is white space. If you set it to some other value, reset it to default whitespace.
Step 2: Read your string to a variable with options -ra. read -ra ARR
Option | Description |
---|---|
-r | Backslash does not act as an escape character. |
-a ARR | The words(separated by IFS) are assigned to the sequential index of array ARR beginning at zero. |
Now you have your string split by the delimiter (set in IFS) stored in array ARR. ARR is just array name. Any string literal that is valid could be used as an array name.
Step 3: You may now access the tokens split into an array using a bash for loop.
Its time for some examples. In the following two examples, we will go through example bash scripts where we use IFS to split a string.
Example 1: Bash Split String by Space
In this example, we split a string using space as a character delimiter.
Bash Script File
#!/bin/bash str="Learn to Split a String in Bash Scripting" IFS=' ' # space is set as delimiter read -ra ADDR "; do # access each element of array echo "$i" done
Run the above bash shell script in a terminal.
$ ./bash-split-string-example Learn to Split a String in Bash Scripting
Example 2: Bash Split String by Symbol
Sometimes we may need to split a string by a delimiter other than space. To split a string in bash shell by a symbol or any other character, set the symbol or specific character to IFS and read the string to a variable with the options -ra mentioned in the below example.
Bash Script File
#!/bin/bash str="Learn-to-Split-a-String-in-Bash-Scripting" IFS='-' # hyphen (-) is set as delimiter read -ra ADDR "; do # access each element of array echo "$i" done IFS=' ' # reset to default value after usage
Run the above bash shell script in terminal.
$ ./bash-split-string-example-1 Learn to Split a String in Bash Scripting
The default value of IFS is single space ‘ ‘ . We changed the value of IFS to split a string. It should not affect any further script that is dependent on IFS. So, assign the default value back to IFS.
Split String with multiple character delimiter
To split a string with a multiple character delimiter (or simply said another string), following are two of the many possible ways, one with idiomatic and the other with just basic bash if and bash while loop.
Example 3: Split String with another string as delimiter idiomatic expressions
In this example, we will use idiomatic expressions where parameter expansion is done, and thus a very compact script.
Bash Script File
#!/bin/bash str="LearnABCtoABCSplitABCaABCString" delimiter=ABC s=$str$delimiter array=(); while [[ $s ]]; do array+=( "$" ); s=$; done; declare -p array
When you run the above script in a Bash Shell, you will see an output similar to the following
$ ./bash-split-string-example-3 declare -a array='([0]="Learn" [1]="to" [2]="Split" [3]="a" [4]="String")'
Following Parameter-Expansions are used (Reference: Bash Man Page[https://linux.die.net/man/1/bash])
Expansion | Description |
$ | Remove the longest matching suffix pattern. |
$ | Remove shortest matching prefix pattern. |
Example 4: Bash Split a String with multiple character delimiter
If you are new to bash shell scripting and are not familiar with idiomatic expressions, following is an easily understandable shell script with basic bash if, bash while and bash substring methods. Comments are provided at each step to make the script file more readable.
Bash Script File
#!/bin/bash # main string str="LearnABCtoABCSplitABCaABCStringABCinABCBashABCScripting" # delimiter string delimiter="ABC" #length of main string strLen=$ #length of delimiter string dLen=$ #iterator for length of string i=0 #length tracker for ongoing substring wordLen=0 #starting position for ongoing substring strP=0 array=() while [ $i -lt $strLen ]; do if [ $delimiter == $ ]; then array+=($) strP=$(( i + dLen )) wordLen=0 i=$(( i + dLen )) fi i=$(( i + 1 )) wordLen=$(( wordLen + 1 )) done array+=($) declare -p array
$ ./bash-split-string-example declare -a array='([0]="Learn" [1]="to" [2]="Split" [3]="a" [4]="String" [5]="in" [6]="Bash" [7]="Scripting")'
The split strings are stored in the array and could be accessed using an index.
Conclusion
In this Bash Tutorial, we have learned how to split a string using bash script with different scenarios based on delimiter: like single character delimiter and multiple character delimiter.