Substring in UNIX she scripting

In the UNIX shell script ( I have a following string '00000101'.  How do I strip leading zero from this string so I will end up with '101'?  Please note every run produces different number, so the number of leading zeros may vary ( Ex: 00000090 or 00002101).

Thanks in advance,
Who is Participating?
omarfaridConnect With a Mentor Commented:
try this


string=`expr $string + 0`

echo $string
ane4kaAuthor Commented:
This worked!!!!

string=`expr $string\ + 0`

I know the question is already complete but I will answer it anyway.

As long as your using Ksh or Bash, you can use:


What this does, is find the part of the string up to a digit that isnt a 0 ${string%%[1-9]*} giving 00000 (or however many leading 0's there are).  Actually, %% finds the largest (donated by using two %'s instead of one) part of the string matching pattern but anchored to the tail end of the string, and then (here's the catch) returns everything but the matching part.  So in your 00000101 example, it finds 101, then returns everything but the 101.

We then uses the resulting pattern to return everything after that pattern ${string#00000}, the ${string#00000} being anchored to the start of the string and returning everything but what matches the pattern.  One # means find the smallest match although in this case it would not matter if we used ## as we are not using any wildcards.

Looks rather complicated and still to this day, I usually have to test out such expressions separatly to make sure I have got them the correct way around (I forget which is anchored to the start and end usualy), but it avoids using an external process which is why I prefer to use them when I can.
All Courses

From novice to tech pro — start learning today.