Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Stripping leading zero's off a string. 2

Status
Not open for further replies.

alqsp

Programmer
Dec 12, 2001
9
AU
Scenario:
I'm reading in an ascii file with a header record that has several fields. Layout is:
@@@XXXXXXXXXX999999999DD-MMM-CC999999999
e.g
@@@TEST 00000000301-MAR-02000000025

Where:
@@@ - Identifies the header record
XXXXXXXXXX - File identifier
999999999 (1st) - A run number with leading zero's
DD-MMM-CC - Date
999999999 (2nd) - A Line count with leading zero's

Two of these fields are numbers that I am able to read in by piping the header record to a cut command based on set positions:

RUNNUMBER=`head -1 $FILE | cut -c14-22`
LINECOUNT=`head -1 $FILE | cut -c32-40`

From the example above giving RUNNUMBER = 000000003 and LINECOUNT = 000000025.

My problem is that I need to validate these numbers against numbers read in as parameters e.g
LASTRUNNUM=2
ACTUALLINECOUNT=25

Validation would be something like:
if [[ ! $LINECOUNT = $ACTUALLINECOUNT ]]
then
<report error>
else
<process normally>
fi

And:
if [[ ! $RUNNUMBER > $LASTRUNNUM ]]
then
<report error>
else
<process normally>
fi

I think the best way to compare these numbers would be to strip the leading zero's from the fields read in from the header record. Could someone suggest how to do this?

If not then any other suggestions on what to do?

Cheers!
 
the [ ] syntax is shorthand for calling TEST. Do a

man test

and you will see test will evaluate parameters differently. if you use

= !=

test will assume strings whereas if you use

-eq -ne

test will assume numbers. therefore

if [[ ! $LINECOUNT = $ACTUALLINECOUNT ]]

compares them as strings

if [[ ! $LINECOUNT -eq $ACTUALLINECOUNT ]]

compares them as numbers.

to validate if there is anything wrong with your numbers you can try

# grep for any character other than 0-9
a=`echo $LINECOUNT | egrep &quot;[^0-9]&quot;`
if [[ $a = $LINECOUNT ]]
then
echo &quot;Please enter only numeric values&quot;
exit
fi



 
You could strip the leading zeros in korn shell by doing this :-

----------------------
#!/bin/ksh

typeset -LZ LINECOUNT
LINECOUNT=0000001234

echo $LINECOUNT
-----------------------

1234

Matt.


 
I would go with tdatgod answer, but Unix always provide two or three ways to skin a cat...
The script...
#! /usr/bin/ksh
NUM=000000000001
echo $NUM
NUM2=${NUM##*0}
echo $NUM2

STR='@@@@@@@@@@@@@@@TEXT'
echo $STR
STR2=${STR##*@}
echo $STR2

Produces...

000000000001
1
@@@@@@@@@@@@@@@TEXT
TEXT
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top