Bash Split StringIn this topic, we have defined how to split a string in bash shell scripting. In some cases, we might need to split the string data to perform some specific tasks. Most of the programming languages contain built-in function 'split' to divide any string data into multiple parts. However, bash does not contain such type of built-in function. But we can use delimiters to split any string data in bash scripting. The delimiter can be either a single character or a string with multiple characters. Check out the methods below to understand how to split string in a bash shell: Split using $IFS variableFollowing are the steps to split a string in bash using $IFS:
Let's understand this mechanism with the help of some examples: Example 1: Bash Split String by SpaceIn this example, a string is split using a space character delimiter. Bash Script Output If we input a string "We welcome you on Javatpoint", the output will look like this: Example 2: Bash Split String by SymbolIn some cases, we may have a requirement to split a string by other delimiters such as a symbol or specific character. In this example, a string is split using a comma (,) symbol character as a delimiter. Bash Script Output Split without $IFS variableIn bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form. Let's understand this logic with the help of some example: Example 1: Bash Split String by SymbolThis example defines how a string value can be split without using $IFS. As per the script, a text value should be entered with the colon (:) sign so that it can be split. Check out the bash script below: Bash Script Output Example 2: Bash Split String by another stringIn this example, we have used idiomatic expressions where parameter expansion has completed. Bash Script In this bash script, we have used the following Parameter- Expansions:
Output Example 3: Bash Split String using Trim CommandIn this example, we have used trim (tr) command to split a string. Instead of using the read command, the trim command is used to split a string on the delimiter. Bash Script Output Note: It should be noted that array elements are divided on 'space delimiter' if we apply a trim command to split a string. For example, elements like 'Windows OS' will be treated as two different words.ConclusionIn this topic, we demonstrated how to split a string in bash scripting with different types of scenarios with or without using delimiter.
Next TopicBash Substring
|