[英]How to remove leading zeros from a variable?
I am trying to remove all the zeros in front of a variable in bash. 我试图删除bash中变量前面的所有零。 But I am not able to save it in the variable.
但是我无法将其保存在变量中。 Some help
一些帮助
the problem is here: if (( $line > $lastMin )) ; then
问题出在这里:
if (( $line > $lastMin )) ; then
if (( $line > $lastMin )) ; then
a Bash error run because value too large for the base (the error element is "0455233") Bash错误运行,因为该值对于基数太大(错误元素为“ 0455233”)
That's why I'm trying to save that value by removing all the zeros I find in front of me 这就是为什么我试图通过删除在我面前发现的所有零来保存该值的原因
Any solutions please? 有什么解决办法吗?
lastMin=0455233
zeroMin=$(( $lastMin | sed 's/^0*//' ))
lastMin='0455233'
zeroMin=$((10#$lastMin))
Removing all leading 0
's; 删除所有前导
0
;
lastMin='0000455233'
zeroMin=$(echo "$lastMin" | sed 's/^0*//')
echo "$zeroMin" # output : 455233
Your problem is caused by using $((
instead of $(
, and not echo
'ing the old var. 您的问题是由于使用
$((
而不是$(
,而不echo
显旧var。
The arithmetic expansion $(( ... ))
is for, well, arithmetics. 算术扩展
$(( ... ))
用于算术。 The |
|
is "binary OR" operation inside $(( ... ))
. 是
$(( ... ))
“二进制或”运算。
You just want to pipe the variable value to stdout of another command, ex. 您只想将变量值通过管道传递到另一个命令的标准输出,例如。
sed
. sed
。
On posix compatible shells you can use a simple pipe |
在posix兼容的shell上,您可以使用简单的管道
|
with process substitution $()
: 用进程替换
$()
:
zeroMin=$(printf "%s\n" "$lastMin" | sed 's/^0*//')
# or a little tiny bit less portable version with echo
zeroMin=$(echo "$lastMin" | sed 's/^0*//')
On bash you can use use here strings <<<
: 在bash上,您可以在此处使用use字符串
<<<
:
zeroMin=$(<<<$lastMin sed 's/^0*//')
You don't need to spawn a separate process for this, just use parameter expansions : 您不需要为此生成单独的过程,只需使用参数扩展即可 :
$ a=01234
$ b=00001234
$ c=1234
$
$ echo "${a#${a%%[1-9]*}}"
1234
$ echo "${b#${b%%[1-9]*}}"
1234
$ echo "${c#${c%%[1-9]*}}"
1234
${var%%[1-9]*}
will remove longest suffix beginning with a digit between 1 and 9 from var
; ${var%%[1-9]*}
将删除与来自图1和9之间的数字开头最长后缀var
; so it will leave leading zeroes, and now that you have leading zeroes you can remove them from var
using ${var#${var%%[1-9]*}}
. 因此它将留下前导零,现在您有了前导零,您可以使用
${var#${var%%[1-9]*}}
从var
中将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.