简体   繁体   English

如何从shell中的负数中删除前导零

[英]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? 有什么简单的方法可以从Shell中的负数中删除前导零? For example : for a number like -02, the output will be -2 例如:对于像-02这样的数字,输出将为-2

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 : bc

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

What about using the builtin printf ? 使用内置的printf怎么样?

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

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? 对于浮动有什么办法吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM