在 sed 替换中添加前导 0 [英] Add leading 0 in sed substitution

查看:31
本文介绍了在 sed 替换中添加前导 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有输入数据:

foo 24
foobar 5 bar
bar foo 125

我想要输出:

foo 024
foobar 005 bar
bar foo 125

所以我可以使用这个 sed 替换:

So I can use this sed substitutions:

s,\([a-z ]\+\)\([0-9]\)\([a-z ]*\),\100\2\3,
s,\([a-z ]\+\)\([0-9][0-9]\)\([a-z ]*\),\10\2\3,

但是,我可以做一个替换吗,那也一样吗?类似的东西:

But, can I make one substitution, that will do the same? Something like:

if (one digit) then two leading 0
elif (two digits) then one leading 0

问候.

推荐答案

我怀疑if - else"逻辑可以合并到 one 替换命令中而不保存中间数据(长度例如匹配).不过,这并不意味着您不能轻松做到.例如:

I doubt that the "if - else" logic can be incorporated in one substitution command without saving the intermediate data (length of the match for instance). It doesn't mean you can't do it easily, though. For instance:

$ N=5
$ sed -r ":r;s/\b[0-9]{1,$(($N-1))}\b/0&/g;tr" infile
foo 00024
foobar 00005 bar
bar foo 00125

它使用递归,在循环中比$N 位短的所有数字加一个零,循环结束时无法进行更多替换.r 标签基本上表示:尝试进行替换,然后 goto r 如果找到要替换的内容.在 sed 中查看更多关于流量控制的信息这里.

It uses recursion, adding one zero to all numbers that are shorter than $N digits in a loop that ends when no more substitutions can be made. The r label basically says: try to do substitution, then goto r if found something to substitute. See more on flow control in sed here.

这篇关于在 sed 替换中添加前导 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆