Linux bash split string

Bash split string into array using 4 simple methods

Table of Contents

How to create array from string with spaces? Or In bash split string into array? We can have a variable with strings separated by some delimiter, so how to split string into array by delimiter?

The main reason we split string into array is to iterate through the elements present in the array which is not possible in a variable.

Sample script with variable containing strings

For example in this script I have a variable myvar with some strings as element

Here if I want to iterate over individual element of the myvar variable, it is not possible because this will considered as a variable and not an array.
This we can verify by counting the number of elements in the myvar variable

When we execute the script, we see that number of elements in myvar is 1 even when we have three elements

To overcome this we convert and split string into array. Now your variable can have strings or integers or some special characters, so depending upon your requirement you can choose different methods to convert string into an array. I will cover some of them with examples:

Method 1: Bash split string into array using parenthesis

Normally to define an array we use parenthesis () , so in bash to split string into array we will re-define our variable using open and closed parenthesis

Snippet from my terminal

Method 1

Next execute the shell script. We see know we have 3 elements in the array

Method 2: Bash split string into array using read

We can use read -a where each input string is an indexed as an array variable.
the default delimiter is considered as white space so we don’t need any extra argument in this example:

Snippet from my terminal

Method 2

Execute the script. Now the myarray contains 3 elements so bash split string into array was successful

Method 3: Bash split string into array using delimiter

We can combine read with IFS (Internal Field Separator) to define a delimiter.
Assuming your variable contains strings separated by comma character instead of white space as we used in above examples
We can provide the delimiter value using IFS and create array from string with spaces

Snippet from my terminal

Method 3

Execute the shell script, and the variable is successfully converted into array and the strings can be iterated separately

Method 4: Bash split string into array using tr

tr is a multi purpose tool. We will use this tool to convert comma character into white space and further using it under parenthesis from Method 1 to create array from string with spaces
So you can use this with any other delimiter, although it may not work under all use cases so you should verify this based on your requirement

Snippet from my terminal

Method 4

Execute the shell script

Some more examples to convert variable into array in bash

Based on your requirement you can choose the preferred method.

For example here I have a variable with newline as delimiter. So here I can use the first method. This will create array from string with spaces

Читайте также:  Драйвер для сканера canon mf4450 для windows 10

Execute the script. You can verify using the number of elements in the array

We can now iterate through the elements which are part of the array in a loop

Execute the script to verify

Lastly I hope the steps from the article for bash split string into array on Linux was helpful. So, let me know your suggestions and feedback using the comment section.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

4 thoughts on “Bash split string into array using 4 simple methods”

Tks. Great. Can we use the array element “$” for regex search in grep/sed/awk. If so, some examples pl.

Can you please give an example so I can help you

I found Method 3 did not work for me… Here is the slightly modifed script:

(Modified to show the bash version in use and the contents of the first array entry…)

Here is what I get:

It is possibly because my bash version is prehistoric, but I remain surprised that I get no error messages. Interesting the commas have gone when it lists My array[0] despite IFS initialisation…

Источник

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

Run the above bash shell script in a terminal.

Output

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

Run the above bash shell script in terminal.

Output

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

When you run the above script in a Bash Shell, you will see an output similar to the following

Output

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

Output

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.

Источник

How to Split String in Bash Script

Let’s say you have a long string with several words separated by a comma or underscore. You want to split this string and extract the individual words.

You can split strings in bash using the Internal Field Separator (IFS) and read command or you can use the tr command. Let me show you how to do that with examples.

Method 1: Split string using read command in Bash

Here’s my sample script for splitting the string using read command:

The part that split the string is here:

Let me explain it to you. IFS determines the delimiter on which you want to split the string. In my case, it’s a semi colon. It could be anything you want like space, tab, comma or even a letter.

The IFS in the read command splits the input at the delimiter. The read command reads the raw input (option -r) thus interprets the backslashes literally instead of treating them as escape character. The option -a with read command stores the word read into an array in bash.

In simpler words, the long string is split into several words separated by the delimiter and these words are stored in an array.

Now you can access the array to get any word you desire or use the for loop in bash to print all the words one by one as I have done in the above script.

Here’s the output of the above script:

Method 2: Split string using tr command in Bash

This is the bash split string example using tr (translate) command:

This example is pretty much the same as the previous one. Instead of the read command, the tr command is used to split the string on the delimiter.

The problem with this approach is that the array element are divided on ‘space delimiter’. Because of that, elements like ‘Linux Mint’ will be treated as two words.

Here’s the output of the above script:

That’s the reason why I prefer the first method to split string in bash.

I hope this quick bash tutorial helped you in splitting the string. In a related post, you may also want to read about string comparison in bash.

And if you are absolutely new to Bash, read our Bash beginner tutorial series.

Источник

Bash Split String 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.

split1.sh

#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 » $ » ;
do
printf » $val \n »
done

Output:

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

#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 : $ »
echo «Author Name : $ »
echo «Price : $ «

Output:

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

#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 » $ »
done

Output:

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

#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 «

Output:

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.

Источник

Читайте также:  Сломался проводник windows 10
Оцените статью