Linux split by space

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

Читайте также:  Как перезаправить картридж epson sx430w

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.

Источник

Bash Scripting – Split String

In this article, we will discuss how to split strings in a bash script.

Dividing a single string into multiple strings is called string splitting. Many programming languages have a built-in function to perform string splitting but there is no built-in function in bash to do so. There are various methods to perform split string in bash. Let’s see all methods one by one with examples.

Method 1: Using IFS variable

$IFS(Internal Field Separator) is a special shell variable. It is used to assign the delimiter(a sequence of one or more characters based on which we want to split the string). Any value or character like ‘\t’, ‘\n’, ‘-‘ etc. can be the delimiter. After assigning the value to the $IFS variable, the string value needs to be read. We can read string using ‘-r’ and ‘-a’ options.

  • ‘-r’: It read backslash(\) as a character instead of an escape character
  • ‘-a’: It is used to store the split-ted words into an array variable that is declared after the -a option.

Example 1: Split the string by space

Code:

Output:

Example 2: Split string by a symbol

String split using @ symbol.

Code:

Output:

Method 2: Without using IFS variable

In this method, readarray command with the -d option is used to split the string data. ‘-d’: this option act as an IFS variable to define the delimiter.

Example 1: Split string by space

Code:

Output:

Example 2: Split using a colon as a delimiter

Code:

Output:

Method 3: Split the string with a multi-character delimiter

In this method, a variable is used to store string data and another variable is used to store multi-character delimiter data. An array variable is also declared to store the split-ted string.

Источник

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.

Источник

Bash shell: 3 examples of how to split strings

Here you will find out:

  • about Bash split strings
  • examples of string separation
  • when DiskInternals can help you

Are you ready? Let’s read!

Bash split strings

Usually, when dealing with string literals or message flows, we sometimes need to split strings into tokens using delimiters. The delimiter can be a single character or a string containing multiple characters. In this tutorial, we will learn how to split strings using single-character length separators and multi-character length separators in Bash shell scripts.

To split a string in Bash, follow these steps:

  • Set IFS to the required delimiter: IFS is an internal variable that determines how Bash recognizes word boundaries.
  • The default value of IFS is blank. If you set it to a different value, reset it to the default space.
  • Use the option -ra to read a string into a variable.

-r backslash cannot be used as an escape character.

-a ARR Words separated by IFS get a sequential index of the ARR.

  • Now split the string into delimiters (set in IFS) stored in the array ARR. ARR is just an array name. Any valid string literal can be used as the array name.
  • Now you can use bash to iterate over tokens split into arrays.

It’s time to give some examples. In the following three examples, let’s go through a Bash script, where IFS is used to split a string.

Источник

Bash Split String into Array

Example 01

We have declared an “str” variable in the shell with a string value in it. Here, we used the “IFS” variable as a delimiter to split a string “str”. The delimiter “IFS” contains “space” as its value. This means the string will split into an array using the space between its values. Now, the “for” loop is used here to iterate the string “str”. Within the “do” clause, each element of an “str” variable will be displayed as an array. After the loop ends, the terminal displays the string in an array form as per the image below.

Example 02

Let’s have another example to get a little different output. You can see clearly that the string contains “,” character after every word in it. This special character will be used as a delimiter. So, we have declared “,” as a value to the “IFS” variable.

]The “for” loop has been initialized here again to iterate the string variable “str”. Within the “do” clause of the “for” loop, the echo statement has been used to display each word separately with the index number as separated by the “IFS” variable value. After the loop ends, the program displays each word of string separately in the form of an array. The character “,” is responsible for this kind of split between string values. As a result, we have got 5 values in the form of an array from a single string variable “str”.

Example 03

Let’s have another example of splitting a string to an array within the bash file. So, you have to create a bash file “test.sh” with a touch query in the shell, as mentioned below.

Now, open the newly created file in an editor to write a bash script in it. We have been utilizing the “GNU Nano” editor for this purpose. You can utilize the vim editor as well.

Within the bash file, we have added the bash extension first to make this code executable with the bash command in the shell. After that, a variable “str” has been declared and initialized with a long string value in it. The “IFS” variable has been declared and assigned with a value “space”. The read statement has been used here to read the data from a string variable “str” as an array with the help of the “-ra” flag and saved to the new variable “Arr”.

The echo statement calculates and displays the size of an “Arr” variable, i.e., array. The “for” loop is here to iterate the values of array values, i.e., “Arr” in a sequence and displayed within the shell using the printf statement. The program ends here. Save your code with the “Ctrl+S” and quit the editor using the “Ctrl+X” shortcut.

Run your newly created bash script with the bash command along with the name of a bash file, i.e., “test.sh”. The execution of the bash script first shows the size of a string “str” i.e., Array. After that, the terminal displayed the values of a string variable in the form of an array, i.e., each word separated. A total of 9 words have been displayed on the shell, as shown below.

Example 04

Let’s make another illustration to split a string into an array. So, open the same code file and update the string variable “str”. We have added 6 words in the string separated by a comma. This comma will be used as a delimiter in the “IFS” variable. The read statement has been reading the words of a string “str” as an array separately and saving each one of them to a variable “Arr”. The delimiter works here and separates each word from a string.

The 6 echo statements have been used here to display every value of the “Arr” variable using the indexes of words. You can see the syntax for taking every value by index in the shown image.

After running the code in the shell with the help of a bash query, we have got 6 lines of output. Every word of a string is separately saved into the array variable “Arr” and displayed with the help of indexes.

Example 05

Let’s have our last example of splitting a string value into an array. This time, we are not using the “IFS” variable as a delimiter to split a string. We will use the “tr” flag to do so. So, open the file “test.sh” in a Nano editor to update it. Add the bash extension at the first line.

The string type variable “str” has been initialized. Another variable, “Arr” has been using the variable “str” value and splitting it into parts by using the “tr” flag. The “tr” delimiter contains space as its value. The “for” loop is iterating the variable “Arr” values with the help of indexes. Every value will be displayed separately in the form of an array.

After running the bash code, we have got the result in an array form. Every word in a string “str” is separated and converted into an independent value, i.e., Array element.

Conclusion

In this article, we have discussed several examples to split a string value into an array. For this purpose, we have used the delimiter “IFS” variable and “tr” methods. All the examples are quite easy to understand and can be implemented without any issue.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Источник

Поделиться с друзьями
КомпСовет
Adblock
detector