9

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Roman
  • 155
  • 1
  • 2
  • 8
  • 1
    This should help: http://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash – Octopoid Jan 29 '15 at 22:22
  • BTW, `var4=Words and spaces` would run the command `and`, with `spaces` as its first argument, and `var4` set to `Words` in the environment. More accurate to write `var4='Words and spaces'` to show something that behaves equivalently to what you're trying to accomplish. – Charles Duffy Jan 29 '15 at 22:33

1 Answers1

16

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]
anubhava
  • 761,203
  • 64
  • 569
  • 643