Striipping leading zeros from a field in awk

I need to strip some leading zeros in a field that I have extracted from a UNIX text file using awk.

There are two scenarios.

1. The field consistently has a single zero on the left of every row. Unless there is a better way I will use substr() to get rid of that

2. The field has a variable number of zeros padding it on the left. I need to strip away the zeros until I get to the first non-zero character then leave it at that. If I add zero to the field and print the result, will that work? or is there a better way?

For example:

1. 020090101 becomes 20090101
2. 00087887887 becomes 87887887
    00232200222 becomes 00232200222
    1118818100    stays as it is

Who is Participating?
ozoConnect With a Mentor Commented:
awk '{sub(/^0+/,"")}1
stummjAuthor Commented:
This is within an awk script ozo, so what is the syntax to apply it to variable $7 (for example)

Also, if there are more than one leading zero in the first example, will it not screw things up?
Todd MummertConnect With a Mentor Commented:

awk '{sub(/^0+/,"",$7)}'

your addition works as well

awk '{$7+=0}'

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

awk '{sub(/^0+/,"",$7)}1'
what sort of screw up would it do?
would not work if $7 was
why not try
awk '{printf "%d", $7}' <inputfile>
with linefeed -
awk '{printf "%d\n",  $7}' <inputfile>
stummjAuthor Commented:
Well in the first example, where I need to strip off just the first leading zero, if there happened to be 2 zeros at the start, wouldnt it remove both of them?

Thats what I need in the second example but not in the first
I assumed you would want to remove both of them.
Another question might be, what would you want to if it is nothing but zeros
Todd MummertCommented:

just to clarify your last question, this small change to ozo's would remove just the first 0

awk '{sub(/^0/,"",$7)}'
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.