在我的awk命令中有什么问题?

时间:2013-12-23 09:59:42

标签: awk

有人能说出这个命令有什么问题吗?

file.txt包含一些数字

我想将下一个数字打印到零,即每次出现0(完全匹配),我尝试下面的命令

awk '/^0/ {for(i=1; i<=1; i++) {getline; printf("%s,",$0);}}' file.txt

我得到了预期的结果,即

 8,3,31,8,32,33,1,23,16,19,33,15,34,25,14,15,19,16,27,

但是当我尝试将所有下一个数字设为1时,结果并不像预期的那样

awk '/^1/ {for(i=1; i<=1; i++) {getline; printf("%s,",$0);}}' file.txt

结果

20,12,16,9,12,13,2,34,12,9,26,15,28,30,10,29,20,25,24,33,22,7,16,22,33,11,16,11, 10,8,27,14,33,16,2,33,23,11,11,15,17,36,8,16,35,16,3,26,25,35,33,26,17,19,10,4,29,20,3,28,21,29,13,6,15,35,21,31,0,16,2,8,13,12,6,14,7,8,13,15,30,5,15,20,35,27,10,32,16,19,24,35,12,28,18,35,24,7,32,8,4,17,35,17,11,24,0,22,12,15,0,8,10,2,33,25,25,31,28,35,14,19,27,7,31,15,26,17,18,36,1,9,28,19,7,12,0,4,30,28,20,21,14,0,22,19,15,35,7,8,5,1,30,21,

1

的预期结果
12,28,10,2,17,10,4,29,16,0,31,27,0,28,10

同样如果我试图获得2,3,4的发生的下一个数字,.....

任何人都可以说错了吗?

用$ 0更新 - 仍然遇到同样的问题 感谢

4 个答案:

答案 0 :(得分:2)

也许这更好:

awk '/^1$/ {for(i=1; i<=1; i++) {getline; printf("%s,",0);}}' file.txt

使用/^1$/表示整行以1开头...而且只是1。根据您当前的解决方案,/^1/可以匹配以1开头的任何数字:1,10,11,12423432 ......

虽然我会选择:

$ awk '$0==1 {getline; print}' file
12
28
10
2
17
10
4
29
16
0
31
27
0
28
10

答案 1 :(得分:1)

我认为你的问题是以(或等于)1 (or other)开头的连续行。您希望第一行不以1开头。

在这种情况下我不会使用getline,它只会使问题更复杂。检查一下:

0案例:

kent$  awk '/^0/{f=1;next}f{f=0;printf "%s, ", $0}' f 
8, 3, 31, 8, 32, 33, 1, 23, 16, 19, 33, 15, 34, 25, 14, 15, 19, 16, 27,

1例:(完全匹配)

kent$  awk '$0=="1"{f=1;next}f{f=0;printf "%s,", $0}' f 
12,28,10,2,17,10,4,29,16,0,31,27,0,28,10,

1例:(正则表达式匹配)

kent$  awk '/^1/{f=1;next}f{f=0;printf "%s,", $0}' f
20,35,32,9,5,5,2,34,9,26,8,28,30,4,29,20,25,24,33,22,7,22,33,2,25,0,8,27,33,5,2,33,23,3,23,5,36,8,35,5,3,26,25,35,33,26,21,27,30,4,29,20,3,28,21,29,6,2,35,21,31,0,27,2,8,35,6,7,8,8,36,30,5,34,20,35,27,34,32,9,22,24,35,28,25,35,24,7,32,8,4,5,35,23,24,0,22,0,32,0,8,2,33,25,25,31,28,35,7,27,7,31,25,26,20,36,0,9,28,7,0,4,30,28,20,21,22,0,22,21,9,35,7,8,5,30,21

您可以传递01的参数,以使您的awk命令通用。

答案 2 :(得分:0)

您可以尝试以下代码:

awk -vval=0 '
$1 == val {
   getline
   printf("%s,",$0)
}
END {
    print ""
}' file.txt

答案 3 :(得分:0)

尝试:

awk '/^0$/ {getline ; printf("%s,",$1)} ' 

以及1之后的值:

awk '/^1$/ {getline ; printf("%s,",$1)} '