BabaYaga
BabaYaga

Reputation: 529

how to remove leading zeros from negative numbers in shell

Is there any simple way to remove leading zeros from a negative number in shell? For example : for a number like -02, the output will be -2

Upvotes: 0

Views: 504

Answers (3)

fedorqui
fedorqui

Reputation: 290525

What about using the builtin printf?

$ num=-02
$ printf "%d\n" "$num"
-2

Upvotes: 1

Andreas Louv
Andreas Louv

Reputation: 47127

There a multiply ways to do this:

a="-02"
echo "$((a+0))"

Another with regex:

a="-02" 
echo "${a//-0/-}"

Or

a="-02" 
[[ "$a" =~ ^(-*|\+*)0*(.*)$ ]]
echo "${BASH_REMATCH[1]}${BASH_REMATCH[2]}"

And bc:

a="-02"
bc <<< "$a + 0"

Upvotes: 1

BabaYaga
BabaYaga

Reputation: 529

One solution as I know is the following :

echo -02 | awk '{$0=int($0)}1'

but it only works with integer number. For floating is there any way?

Upvotes: 0

Related Questions