Is it possible to pad integers with zeros using regular expressions?

a 夏天 提交于 2019-11-27 20:33:13
Mark Byers

You can pad it with too many zeros and then keep only the last six digits:

sed -e 's/:/:00000/;s/:0*\([0-9]\{6,\}\)$/:\1/'

Result:

A1:000011
A2:000112
A3:223333
A4:001333
A5:019333
A6:000004

It might be better to use awk though:

awk -F: '{ printf("%s:%06d\n", $1, $2) }'

Here is a perl solution :

 perl -n -e 'split /:/;printf("%s:%06d\n", @_)'

You asked a regular expression, so I looked for the colon to split with a regular expression, but in this case a simple string would suffice.

[pti@os5 ~]$ cat tst.txt | perl -n -e 'split /:/;printf("%s:%06d\n", @_)'
A1:000011
A2:000112
A3:223333
A4:001333
A5:019333
A6:000004
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!