简体   繁体   中英

split string in one liner in bash or ksh or perl

var="valueA valueB"

I want to split above string as shown below and want to read those value in one liner on bash shell.

Following script not working .

echo $var |awk '{print $1  $2}' |while read var; do echo  var1=$1 and var2=$2;done 

echo $var |awk '{ var1=$1 ; var2=$2}' |while read var1 var2; do echo  var1=$var1 and var2=$var2;done 

To get those value into var1 and var2 , use:

read var1 var2 <<<"$var"

The above uses a here-string and should work under bash, ksh, or zsh.

The above assumes, by default, that the two values are separated by whitespace. Other separators are possible just by changing the value of the shell's IFS variable.

In bash:

$ read -a foo <<< "$var"
$ set | grep ^foo
foo=([0]="valueA" [1]="valueB")
$ echo "${foo[1]}"
valueB

Following worked for me.

var="valueA valueB"
echo $var |while read var1 var2 ;do  echo $var1 ---- $var2;done

Output will be:

valueA --- valueB

In ksh93, this will work of the shelf:

echo "$var" |
    read var1 var2 &&
        echo $var1 --- $var2

Effectively the same as https://stackoverflow.com/a/32855720/667820 , but the values of $var1 and $var2 are preserved.

For bash, you need bash 4.x and some options need to be (un)set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM