Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to split a string in Bash separated by a colon and assign to variables

Tags:

bash

shell

I have String that always has 4 'words'

Strings:With:Four:Words and spaces

and need to split it into 4 variables in Bash. so..

var1="Strings"
var2="With"
var3="Four"
var4="Words and spaces"

how do I do this?

like image 668
Roman Avatar asked Jan 29 '15 22:01

Roman


People also ask

How do I split a string in bash?

In 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.

What does Colon in bash do?

The : (colon) command is used when a command is needed, as in the then condition of an if command, but nothing is to be done by the command. This command simply yields an exit status of zero (success). This can be useful, for example, when you are evaluating shell expressions for their side effects.

What is $s in bash?

From man bash : -s If the -s option is present, or if no arguments remain after option processing, then commands are read from the standard input. This option allows the positional parameters to be set when invoking an interactive shell. From help set : -e Exit immediately if a command exits with a non-zero status.


1 Answers

Use IFS=: before read:

s='Strings:With:Four:Words'
IFS=: read -r var1 var2 var3 var4 <<< "$s"
echo "[$var1] [$var2] [$var3 [$var4]"
[Strings] [With] [Four [Words]
like image 137
anubhava Avatar answered Nov 15 '22 04:11

anubhava