我正在尝试计算两个相邻字段之间的距离.我的输入文件如下所示.
1 11160 11533 11556 11731 11822 11870 12149 12411 12461 12686 12829 13315 13420 ....
在输出中,我想保留第一个字段,以下字段将是当前字段和下一个字段之间的值差异$2=$3-$2,$3=$4-$3...
完整的输出将是:
1 373 23 175 91 48 279 262 50 225 143 486 105 ......
我怎样才能做到这一点?
在我的代码中,每个值都打印为一个新行,同时反向打印数字.
BEGIN {FS=" "}
{
out[1]=$1
for (i=2;i<=NF-1;i++)
out[i]=$(i+1)-$i
}
END{
for (i in out)
print out[i]
}
Run Code Online (Sandbox Code Playgroud)
这是当前的输出
373 23 175 91 48 279 262 50 225 143 486 105 1
编辑:在评论部分添加 anubhava 先生建议的代码。
awk '{s=$1; for (i=2; i<NF; i++) s = s OFS $(i+1) - $i; print s}' Input_file
Run Code Online (Sandbox Code Playgroud)
您可以尝试以下吗?
awk '{printf $1 OFS;for(i=2;i<NF;i++){printf("%d%s",$(i+1)-$i,i==(NF-1)?ORS:OFS)}}' Input_file
Run Code Online (Sandbox Code Playgroud)
输出如下。
1 373 23 175 91 48 279 262 50 225 143 486 105
Run Code Online (Sandbox Code Playgroud)
解释:这里也添加解释。
awk '
{
printf $1 OFS ##Printing first field and OFS(whose value is space by default).
for(i=2;i<NF;i++){ ##Starting for loop from value of 2 to till NF-1 value where NF is number of field in current line.
printf("%d%s",$(i+1)-$i,i==(NF-1)?ORS:OFS) ##Printing diffrence of next field and current field and checking condition for 2nd print if i==NF-1 then new line else print space for that line.
} ##Closing for loop block here.
}
' Input_file ##Mentioning Input_file name here.
Run Code Online (Sandbox Code Playgroud)