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?
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With