2011-02-18 55 views
1

我有一个简单的问题,我想,但我找不到解决方案。
一个简单的perl脚本会打印出以下行"tests - Blub" "tests - Blub - Abc",我将它分配给一个像var=$(perl ...)这样的变量,但为什么我不能将它解析为数组varArray=($var),并且该命令varArray=("tests - Blub" "tests - Blub - Abc")有效?解析值到数组

预期的结果应该是这样的:

tests - Blub 
tests - Blub - Abc 

,而不是像这样:

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

感谢您的任何建议。

+0

什么shell /版本? – 2011-02-18 19:51:58

+0

Linux bash版本3.2.39。 – CSchulz 2011-02-18 19:54:02

回答

2

下面是一些涂鸦:

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

显然第三结果是你想要的。当您从Perl脚本的输出中填充变量时,其中的双引号对shell没有特殊含义:它们只是字符。你必须得到shell来解析它(用eval),这样它们的含义就暴露了。

1

我做了以下内容:

$ 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] 

这告诉我,()构造忽略可变扩展后,双引号。此外,当我做

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

我得到了类似的结果:

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

貌似变量替换发生,而不是在后来又看了看前引号的处理方式。

0

如何将xargs与sh -c'...'结合使用?

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