简体   繁体   English

从数字中删除前导零

[英]Remove leading zeros from number

How to convert all numbers in Bash/shell?如何转换 Bash/shell 中的所有数字?

VAR=00005
VAR=00010
VAR=00601
VAR=00550

to

echo $VAR #5
echo $VAR #10
echo $VAR #601
echo $VAR #550
$> cat text    
00005
00010
00601
00550

$> sed -r 's/0*([0-9]*)/\1/' text    
5
10
601
550

Using printf :使用printf

$> while read n; do printf "%0d\n" $((10#$n)); done < text
5
10
601
550

Note, when a numerical format expects a number, the internal printf-command will use the common Bash arithmetic rules regarding the base.请注意,当数字格式需要数字时,内部 printf 命令将使用有关基数的常见 Bash 算术规则。 In order to force decimal representation and as a side effect also remove any leading zeros for a Bash variable we should use $((10#$n))为了强制十进制表示并作为副作用还删除 Bash 变量的任何前导零,我们应该使用$((10#$n))

The reason people are having issues with 08 and 09 is because numbers with trailing zeros are treated by the shell as octals.人们对0809有问题的原因是因为带有尾随零的数字被 shell 视为八进制。 You can do something like this:你可以这样做:

VAR="08"
let "VAR=10#${VAR}"
echo $VAR

to remove the trailing zeros.删除尾随零。

or like this:或者像这样:

kent$  echo "00005
00010
00601
00550"|awk '$0*=1'
5
10
601
550

for your updated question (with VAR)对于您更新的问题(使用 VAR)

first of all, you should have different variable names, not all same as VAR.首先,你应该有不同的变量名,与 VAR 不同。

see the example below:看下面的例子:

kent$  VAR=00601

kent$  VAR=$((VAR+0))

kent$  echo $VAR
601

EDIT编辑

for the comment.(08, 09 didn't work):对于评论。(08, 09 无效):

08, 09 worked here, might be something with my shell to do. 08、09在这里工作过,可能是我的shell有事要做。 I have zsh.我有zsh。 I tested followings under bash, they worked.我在 bash 下测试了以下内容,它们奏效了。 hope helps:希望有帮助:

under zsh:在 zsh 下:

kent$  v=08

kent$  v=$((v+0))

kent$  echo $v
8

under bash, below worked在 bash 下,下面的工作

kent@7PLaptop:/tmp$ bash -version
GNU bash, version 3.2.48(1)-release (i486-pc-linux-gnu)
Copyright (C) 2007 Free Software Foundation, Inc.
kent@7PLaptop:/tmp$ v=08
kent@7PLaptop:/tmp$ v=$(sed 's/^0*//'<<< $v)
kent@7PLaptop:/tmp$ echo $v
8

With extglob , you do not need any external process:使用extglob ,您不需要任何外部进程:

shopt -s extglob                       # Enable extended globbing
for i in 00005 00010 00601 00550; do
    echo ${i##+(0)}
done

echo $((10#${VAR}))可以做你想做的

You can use printf to add or remove leading zeros:您可以使用printf添加或删除前导零:

$ printf "%05d\n" 5    
00005

$ printf "%d\n" 00005
5

$ printf "%010d\n" 00005
0000000005

to: ДМИТРИЙ МАЛИКОВ至: ДМИТРИЙ МАЛИКОВ

printf "%d\n" 0000
printf "%d\n" 0001
printf "%d\n" 0002
printf "%d\n" 0003
printf "%d\n" 0007
printf "%d\n" 0008
printf "%d\n" 0009
printf "%d\n" 0010
printf "%d\n" 0011
printf "%d\n" 0012

result结果

0
1
2
3
7
0 line 8: printf: 0008: invalid octal number
0 line 9: printf: 0009: invalid octal number
8 !error - correctly 10
9 !error - correctly 11
10 !error - correctly 12

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

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