从文字变量输入创建序列



我试图创建如下序列:

startDay=1
endDay=2
dayRange="{$startDay..$endDay}"
echo ["$dayRange","{00..02}"]

输出为:

["{1..2}","00"] ["{1..2}","01"] ["{1..2}","02"]

当直接指定序列{00..02}时,它自动创建"00", "01", "02",但它不理解dayRange变量。我希望它返回的是:

["1","00"] ["1","01"] ["1","02"] ["2","00"] ["2","01"] ["2","02"] 

不知道我错过了什么。请建议。

第一个想法是一个简单的嵌套for循环:

startDay=1
endDay=2
pfx=
out=
for ((i=startDay; i<=endDay; i++))
do
for j in {00..02}
do
out+="${pfx}["${i}","${j}"]"
pfx=" "
done
done
echo "${out}"

由此产生:

["1","00"] ["1","01"] ["1","02"] ["2","00"] ["2","01"] ["2","02"]

编码少一点,速度快一点,它使用OP的echo ... {00..02}来消除for循环之一:

注意:这就消除了我在前面的编辑中调用的子进程$(echo ...)

startDay=1
endDay=2
for ((i=startDay; i<=endDay; i++))
do
echo -n "[""${i}"",""{00..02}""]"
echo -n " "
done
echo ""

这也产生:

["1","00"] ["1","01"] ["1","02"] ["2","00"] ["2","01"] ["2","02"]

这里有一个awk的想法:

awk -v start=$"${startDay}" -v end="${endDay}" '
BEGIN {
pfx=""
out=""
for (i=start; i<=end; i++)
for (j=0; j<=2; j++) {
out=out pfx "["" i "","" sprintf("%02d", j) ""]"
pfx=" "
}
print out
}'

这也产生:

["1","00"] ["1","01"] ["1","02"] ["2","00"] ["2","01"] ["2","02"]

在消除了较早的子进程$(echo ...)后,前两个解决方案的毫秒时间为一位数,而awk解决方案的毫秒时间为低两位数。

随着天数(和/或序列大小)的增加,前两个解决方案开始花费更长的时间(嵌套的for循环落在后面更远),而awk解决方案倾向于保持相同的速度。

对于真正大的增长(天数和/或序列大小),我预计awk将接近并最终占据领先地位。

相关内容

  • 没有找到相关文章

最新更新