从文字变量输入创建序列
Create sequence from literal variable inputs
我正在尝试创建如下序列:
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
变量。
我对 return 的期望是:
["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 ...)
前 2 个解决方案采用个位数毫秒计时,而 awk
解决方案采用低两位数毫秒计时。
随着天数(and/or 序列大小)的增加,前 2 个解决方案开始花费更长的时间(嵌套的 for
循环进一步落后),而 awk
解决方案趋向于保持同样的速度。
对于非常大的增加(天数 and/or 序列大小),我希望 awk
接近并最终取得领先。
我正在尝试创建如下序列:
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
变量。
我对 return 的期望是:
["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 ...)
前 2 个解决方案采用个位数毫秒计时,而 awk
解决方案采用低两位数毫秒计时。
随着天数(and/or 序列大小)的增加,前 2 个解决方案开始花费更长的时间(嵌套的 for
循环进一步落后),而 awk
解决方案趋向于保持同样的速度。
对于非常大的增加(天数 and/or 序列大小),我希望 awk
接近并最终取得领先。