我可以在AWK的区间表达式中的表达式中使用NR吗?

时间:2012-09-29 01:25:56

标签: awk

好的,我希望这不是一个愚蠢的问题,但如果有帮助的话,我确实难以找到答案的答案,......我有以下awk表达式,我正在研究:

awk '{str="";a=0;while (a++<15) str=str "0,";{ sub(/^.{6}/,"&" "1,",str) }; print str}' sample.txt

Sample.txt 可以是任何文本文件,此时它并不重要,因为它只是驱动重复(这是一种希望结束的手段)。输出看起来像这样(当然取决于Sample.txt文件中有多少行):

0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,

我真正想做的事情是这样的:

awk '{str="";a=0;while (a++<15) str=str "0,";{ sub(/^.{2*NR-1}/,"&" "1,",str) }; print str}' sample.txt

哪个应该生成这样的输出:

1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,

这可能吗?我已经尝试了一切让Awk拿起2*NR-1,但似乎没有任何效果,......我做错了什么?

特里

2 个答案:

答案 0 :(得分:2)

你尝试的方法看起来相当麻烦。您是否考虑过像这样使用awk

awk '{ for (i=1; i<=15; i++) printf (NR == i) ? "1," : "0,"; printf "\n" }' file.txt

答案 1 :(得分:1)

你也可以使用coreutils,sed和bash的组合:

s=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
seq 16 | while read; do sed 's/0/1/'$REPLY <<< $s; done