开发者

parsing values into array

开发者 https://www.devze.com 2023-02-12 12:26 出处:网络
I have a simple question, I think, but I can\'t find the solution for it. A simple perl script prints out following line \"tests - Blub\" \"tests - Blub - Abc\" and I assign it to a variable like that

I have a simple question, I think, but I can't find the solution for it.

A simple perl script prints out following line "tests - Blub" "tests - Blub - Abc" and I assign it to a variable like that var=$(perl ...), but why can't I parse it to an array with varArray=( $var ) and that command varArray=( "tests - Blub" "tests - Blub - Abc" ) works?

The expected result should be like this:

tests - Blub
tests - Blub - Abc

And not like this:

"te开发者_如何学JAVAsts
-
Blub"
"tests
-
Blub
-
Abc"

Thanks for any advices.


Here's some doodling:

$ bash
$ a='"tests - Blub" "tests - Blub - Abc"'
$ ary=( $a ); echo ${#ary[@]}
8
$ ary=( "$a" ); echo ${#ary[@]}
1
$ eval ary=( $a ); echo ${#ary[@]}
2

Clearly the 3rd result is what you want. When you populate your variable from the output of the Perl script, the double quotes within it have no special meaning to the shell: they're just characters. You have to get the shell to parse it (with eval) so that their meaning is exposed.


I did the following:

$ cat >/tmp/test.sh
echo '"tests - Blub" "tests - Blub - Abc"'

$ chmod +x /tmp/test.sh

$ /tmp/test.sh
"tests - Blub" "tests - Blub - Abc"

$ a=`/tmp/test.sh`

$ echo $a
"tests - Blub" "tests - Blub - Abc"

$ arr=($a)

$ echo $arr[1]
"tests[1]

This tells me that () construct ignores double quotes after variable expansions. Moreover, when I do

for i in $a; do echo $i; done

I get a similar result:

"tests
-
Blub"
"tests
-
Blub
-
Abc"

Looks like quotes are handled before variable substitution takes place and not looked at again later.


How about using xargs in combination with sh -c '...' ?

line='"tests - Blub" "tests - Blub - Abc"'
printf '%s' "$line" | xargs sh -c 'printf "%s\n" "$@"' argv0
IFS=$'\n'
ary=( $(printf '%s' "$line" | xargs sh -c 'printf "%s\n" "$@"' argv0) )
echo ${#ary[@]}
printf '%s\n' "${ary[@]}"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号