2017-08-21 26 views
2

我想兩個包含字符串空間轉換到一個數組中的殼,就像這樣:如何將包含空格的字符串轉換爲shell中的數組?

param_values=$(parse_json_with_keys) # then, param_values: "select * from t" "terry" 

當我將它們轉換爲數組:

param_values=(${param_values}) 
echo ${param_values[0]} # output: "select 
echo ${param_values[1]} # output: * 

但我希望輸出:

echo ${param_values[0]} # output: select * from t 
echo ${param_values[1]} # output: terry 

這讓我很困惑。有人能幫助我嗎?非常感謝!

+0

這意味着,它在限定空白空間,並將其分配給變量。 – LethalProgrammer

+0

parse_json_with_keys的輸出是什麼?來自parse_json_with_keys的字符串是否由「\ n」分隔? – Abis

+0

@Abis parse_json_with_keys將輸出:「select * from t」「terry」 – ouyangyewei

回答

0

因爲我沒有找到更短的方法,下面的代碼將首先刪除第一個和最後一個"。之後,字符串被" "分開。爲了分離,它被替換爲#,它將被用作分隔符,然後存儲到一個數組中。
請注意," "#不允許通過此方法在一個子字符串中。

#!/bin/sh 
values=$(echo '"select * from t" "terry"') 
echo "$values" 

echo "Remove first and last <\"> character:" 
values="${values%\"}" 
values="${values#\"}" 
echo "$values" 

echo "Replace <\" \"> by <#> and split by <#>:" 
sep='" "' 
IFS='#' read -r -a values <<< "${values//$sep/$'#'}" 
for element in "${values[@]}" 
do 
    echo "$element" 
done 

輸出:

$ ./stringArray.sh 
"select * from t" "terry" 
Remove first and last <"> character: 
select * from t" "terry 
Replace <" "> by <#> and split by <#>: 
select * from t 
terry 
相關問題