【问题标题】:Parse an array in KSH shell?在 KSH shell 中解析一个数组?
【发布时间】:2013-05-24 14:30:01
【问题描述】:

我是 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

这次在

的那一行显示“unexpected token '('
set -A A_RID $(echo $RID | sed 's/,/\ /g').

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

【问题讨论】:

  • 分配给str时缺少反引号,请尝试str=`echo $RID | sed 's/,/\ /g'`(注意行尾的反引号)

标签: arrays linux unix ksh


【解决方案1】:

嗯,对我有用。你有什么版本的 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"

【讨论】:

  • 您好,抱歉回复延迟。这个问题对我来说仍然存在。我不确定为什么代码不适合我!当我尝试运行 read -A A_RID
【解决方案2】:

通过启动脚本

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

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

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

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

此外,您应该恢复您对问题的编辑,其中删除了所需的反引号。

【讨论】:

    猜你喜欢
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多