• Uncategorized

About bash : Bash—Remove-leading-zero-for-numbers-with-double-digits

Question Detail

I have a variable in bash number which contains values 01, 02, 03, 04, 05, 06, 07, 08, 09, 010, 011, 012.

I would like to remove the leading zeros before 010, 011 and 012. I only want to remove the leading zeroes if the number is a double digit number.

How can I achieve this?

Thanks in advance!

Question Answer

Try:

a=”012″
printf ‘%02d\n’ “$((10#${a}))”
12

……………………………………………………
Another way:

a=”014″
printf “%02d\n” $(echo “obase=10;$a” |bc)
14

another one:

[[ $a =~ ^0+[1-9]{2,}$ ]] && a=”$(echo $((10#${a})))”
echo $a

This one will remove all 0s from beginning for 2 or more non-zero digit numbers.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.