简体   繁体   English

BASH - IP 地址中的远程前导零

[英]BASH - Remote leading zero in IP Address

I've got the following bash command, which does remove a leading zero.. but it also removes a single zero which is wrong.我有以下 bash 命令,它确实删除了前导零..但它也删除了一个错误的零。

echo $ip | sed 's/\.0\{1,2\}/\./g' | sed 's/^0\{1,2\}//'

if $ip is 192.168.1.01  the result should be 192.168.1.1
if $ip is 192.168.01.01  the result should be 192.168.1.1
if $ip is 192.168.0.01  the result should be 192.168.0.1
if $ip is 192.168.0.0  the result should be 192.168.0.0
etc

What I'm getting is 192.168.0.0 becomes 192.168.. or 192.168.0.01 becomes 192.168..1我得到的是 192.168.0.0 变成 192.168.. 或 192.168.0.01 变成 192.168..1

Any idea how to do this ?知道如何做到这一点吗?

Thanks谢谢

What you are doing now is replacing any .0 with .你现在正在做的是用.0替换任何.0 . . . This will obviously catch 1.1.0.0 as well.这显然也会捕获1.1.0.0

This will work:这将起作用:

echo $ip | sed 's/\.0\+\([1-9]\)/\.\1/g; s/^0\+//'

Here we are looking for .0[1-9] which will only match a leading 0 that is followed by another number.在这里,我们正在寻找.0[1-9] ,它只会匹配前导 0 后跟另一个数字。 You see I used \\([1-9]\\) which saves the trailing number and is placed into the substitution with \\1 .你看我使用了\\([1-9]\\) ,它保存了尾随数字并用\\1放入替换中。

EDIT :编辑

@tomgalpin made a good point about leading 0s in the beginning. @tomgalpin 在开始时就领先 0 提出了一个很好的观点。 I don't have a smooth way of handling this with one command, so I just appended that as a separate substitution: s/^0\\+// .我没有用一个命令来处理这个问题的顺利方法,所以我只是将其附加为单独的替换: s/^0\\+//

EDIT 2编辑 2

Looks like my solution does not work with --posix option because of the + .看起来我的解决方案不适用于--posix选项,因为+ Replacing this with * will work as well though it is making redundant matches.*替换它也会起作用,尽管它会进行冗余匹配。 Also with -E , it is a little cleaner:还有-E ,它更干净一点:

echo $ip | sed -E 's/\.0*([1-9])/\.\1/g; s/^0*//'

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

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