bash – 如何计算两个相邻字段之间的值差异
发布时间:2020-12-15 21:39:35 所属栏目:安全 来源:网络整理
导读:我正在尝试计算两个相邻字段之间的距离.我的输入文件如下所示. 1 11160 11533 11556 11731 11822 11870 12149 12411 12461 12686 12829 13315 13420 …. 在输出中,我想保留第一个字段,以下字段将是当前字段和下一个字段之间的值差异,$2 = $3- $2,$3 = $4- $3
我正在尝试计算两个相邻字段之间的距离.我的输入文件如下所示.
在输出中,我想保留第一个字段,以下字段将是当前字段和下一个字段之间的值差异,$2 = $3- $2,$3 = $4- $3 … 完整的输出将是:
我怎样才能做到这一点? 在我的代码中,每个值都打印为一个新行,同时反向打印数字. 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] } 这是当前的输出
解决方法
编辑:在评论部分添加anubhava先生建议的代码.
awk '{s=$1; for (i=2; i<NF; i++) s = s OFS $(i+1) - $i; print s}' Input_file 你可以尝试一下吗? awk '{printf $1 OFS;for(i=2;i<NF;i++){printf("%d%s",$(i+1)-$i,i==(NF-1)?ORS:OFS)}}' Input_file 输出如下. 1 373 23 175 91 48 279 262 50 225 143 486 105 说明:此处也添加说明. 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==(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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |