0

我是 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').

你能告诉我哪里做错了吗?提前致谢!

4

2 回答 2

0

嗯,对我有用。你有什么版本的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"
于 2013-05-24T18:41:11.763 回答
0

通过启动脚本

sh scriptname.sh 123,345,456,789...

你让sh执行它,而不是ksh. 设置执行权限scriptname.sh并输入

scriptname.sh 123,345,456,789...

让它执行/bin/ksh。然后,您可以将自己应用于不是来自使用错误 shell 的错误。

此外,您应该在删除所需反引号的地方恢复对问题的编辑。

于 2014-07-09T06:18:22.100 回答