[英]Parse an array in KSH shell?
我是shell編碼的新手。 我的目的是接受CSV格式的命令行參數,將輸入解析為數組。 就像是,
sh scriptname.sh 123,345,456,789...
123,345,456 ..應存儲到數組中。 到目前為止,我已經達到以下目標,
#!/bin/ksh
#get the argument to be parsed
RID=$1
#Parse the argument, remove the space and store into and variable
str=`echo $RID | sed 's/,/\ /g'
#Assign the value to a variable
set -A RIDS $str
#Get the count of arguments in the array
num=${#RIDS[@]}
echo $num
#Display the elements in the array
i=0
while [ $num -gt 0 ] do
echo ${A_RIDS[i]}
i=`expr $1 + 1`
num=`expr $num - 1`
done
但這會引發錯誤,如“錯誤替換”(第7行)
另外,我嘗試了以下方式(一次完成):
set -A A_RID $(echo $RID | sed 's/,/\ /g')
代替
str=`echo $RID | sed 's/,/\ /g'
set -A RIDS $str
這次,它在
set -A A_RID $(echo $RID | sed 's/,/\ /g').
你能告訴我我做錯了什么嗎? 提前致謝!
嗯,為我工作。 您有什么版本的ksh?
$ ksh
$ RID=123,345,456,789
$ set -A A_RID $(echo $RID | sed 's/,/\ /g')
$ printf "%s\n" "${A_RID[@]}"
123
345
456
789
$ ksh --version
version sh (AT&T Research) 93u+ 2012-08-01
根據您的ksh版本,它可以短至
IFS=, read -A A_RID <<< "$RID"
通過啟動腳本
sh scriptname.sh 123,345,456,789...
您讓sh
執行它,而不是ksh
。 在scriptname.sh
上設置執行權限,然后僅輸入
scriptname.sh 123,345,456,789...
由/bin/ksh
執行它。 然后,您可以將自己應用於並非使用錯誤的Shell產生的錯誤。
此外,您應該在刪除了所需的反引號后恢復對問題的編輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.