split a variable into two

Hi,

I have a variable with the value "hello world". I want to split this variable into two, so that i can write "hello" into one variable and "world" into another.

Any idea how to do this?

Thanks,
Sri

I think we can do it this way:

x=`echo $var | cut -d" " -f1`
y=`echo $var | cut -d" " -f2`

Please let me know if we can do it in another way?
Thanks,
Sri

Another one...

set `eval echo $var`
x=$1;
y=$2;

Here is another way
x=`echo $VAR | awk '{print $1}'`
y=`echo $VAR | awk '{print $2}'`

Hi Sri,
I hope the below piece of code will help you. One is using regex and another is using split function.

#!/usr/bin/perl

$var = "hello world";

($first, $second) = $var =~ /([aA-zZ]+)\s+([aA-zZ]+)/;
($f, $s ) = split( /\s/, $var );

print " First : $first --- Second : $second \n";
print " First : $f --- Second : $s \n";

Thanks and regards,
J. Ayyappaswami.

Alternative way

$ var="hello world"
$ echo $var |read var1 var2
$ echo $var1
hello
$ echo $var2
world

Another allternative way :slight_smile:

>MESSAGES="hello world"
>PART1=${MESSAGES% }
>PART2=${MESSAGES#* }
>echo $PART1
>echo $PART2

Best regards

Use shell parameter expansion; there is no need for any external command:

var="hello world"
left=${var%% *}
right=${var#* }

Why eval and echo?

set -f  ## inhibit filename expansion
set -- $var
set +f
left=$1
right=$2

Yes ..It is unnecessary

Another (bash):

var="hello world"
declare -a array
array=( $(echo ${var}) )
echo ${array[0]}
echo ${array[1]}

You don't need echo or command substitution (or declare), but you should add set -f in case there are any wildcards in $var:

set -f
array=( $var )
set +f

Or:

printf "%s\n" "${array[@]}"