2011-02-18 60 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[@]}"