Removing Leading Zeros within awk file [duplicate]

安稳与你 提交于 2019-12-14 00:09:53

问题


I am generating a report using an awk file to pull data and write to another file. Filename: dosreport.awk. This code prints a material number like this 000000000000787301

if (substr($0, 1, 7) == "E2EDP19" && E2EDP19seen == 1)
                {
                    printf " " substr($2, 6);
                    E2EDP19seen=E2EDP19seen +1;
                }

The relevant data is E2EDP19001 02002000000000000797578 I need the leading zeros stripped to just give me 787301. Again, this is within an awk file, so piping to an awk command will not work.

Typecasting the original printf will give me the expected value. Working code

if (substr($0, 1, 7) == "E2EDP19" && E2EDP19seen == 1)
                {
                    if (substr($2, 6)+0 == 0)
                    {
                        printf " " substr($2, 6);
                    }
                    else{
                        printf " " substr($2, 6)+0;
                    }
                    E2EDP19seen=E2EDP19seen +1;
                }

回答1:


Try this: sub(/^0+/, "", $2)?

$ awk 'BEGIN{b="000000000000787301"; sub(/^0+/, "", b); print b;}'
787301

or typecast it by adding zero:

$ awk 'BEGIN{b="000000000000787301"; print b+0;}'
787301

update A working example based on comments:

$ echo 'E2EDP19001 02002000000000000797578' | awk '{$2 = substr($2,6); sub(/^0+/, "", $2); print $2;}'
797578

or, preserve $2:

$ echo 'E2EDP19001 02002000000000000797578' | awk '{a = substr($2,6); sub(/^0+/, "", a); print a;}'
797578

up-update Based on revised post, here's a working sample, just like I proposed many, many revisions ago:

sub()

$ echo 'E2EDP19001                                                   02002000000000000797578' \
   | awk 'BEGIN {E2EDP19seen = 1 } 
       {if (substr($0, 1, 7) == "E2EDP19" && E2EDP19seen == 1) {
       out = substr($2, 6); sub(/^0+/, "", out); print out } }'
797578

typecast

$ echo 'E2EDP19001                                                   02002000000000000797578' \
  | awk 'BEGIN {E2EDP19seen = 1 } 
      {if (substr($0, 1, 7) == "E2EDP19" && E2EDP19seen == 1) {
      print substr($2, 6) + 0 } }'
797578


来源:https://stackoverflow.com/questions/23111713/removing-leading-zeros-within-awk-file

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