我想在索引变量中运行一个带有前导零的for
循环。awk
这不是为了印刷一个带有前导零的数字,我可以通过printf
语句轻松处理它。它用于检查给定数字(带前导零)是否已用作数组中的索引。
所以我真正想要的是迭代细绳中的值awk
,从“01”到“14”(或其他)。
就像是:
myarray["01"]
myarray["02"]
myarray["04"]
myarray["05"]
# ... etc, up to "12"
for (i = 01; i <= 12; i++) {
if (! (i in myarray)) {
print i " is missing from myarray"
}
}
应报告“myarray 中缺少 03”。但事实并非如此。
我怎样才能做到这一点?
答案1
只需使用sprintf
:
BEGIN {
myarray["01"]
myarray["02"]
myarray["04"]
myarray["05"]
# ... etc, up to "12"
for (i = 1; i <= 12; i++) {
k = sprintf("%02d", i)
if (! (k in myarray)) {
print k " is missing from myarray"
}
}
}
给你:
03 is missing from myarray
06 is missing from myarray
07 is missing from myarray
08 is missing from myarray
09 is missing from myarray
10 is missing from myarray
11 is missing from myarray
12 is missing from myarray