Replace blank fields with zeros in AWK

跟風遠走 提交于 2021-02-08 05:59:00

问题


I wish to replace blank fields with zeros using awk but when I use sed 's/ /0/' file, I seem to replace all white spaces when I only wish to consider missing data. Using awk '{print NF}' file returns different field numbers (i.e. 9,4) due to some empty fields

input

590073920  20120523 0    M $480746499      CM C 500081532  SP    
501298333           0    M *BB   
501666604           0    M *OO    
90007162            7    M +178852   
90007568            3    M +189182   

output

590073920  20120523 0    M $480746499      CM C 500081532  SP    
501298333  0         0    M *BB             0 0 0          0   
501666604  0         0    M *OO             0 0 0          0 
90007162   0         7    M +178852         0 0 0          0
90007568   0         3    M +189182         0 0 0          0

回答1:


Using GNU awk FIELDWIDTHS feature for fixed width processing:

$ awk '{for(i=1;i<=NF;i++)if($i~/^ *$/)$i=0}1' FIELDWIDTHS="11 9 5 2 16 3 2 11 2" file | column -t
590073920  20120523  0  M  $480746499  CM  C  500081532  SP
501298333  0         0  M  *BB         0   0  0          0
501666604  0         0  M  *OO         0   0  0          0
90007162   0         7  M  +178852     0   0  0          0
90007568   0         3  M  +189182     0   0  0          0


来源:https://stackoverflow.com/questions/24801602/replace-blank-fields-with-zeros-in-awk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!