Question

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;
                }
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top