是否可以使用正则表达式将整数填充为零? [英] Is it possible to pad integers with zeros using regular expressions?

查看:79
本文介绍了是否可以使用正则表达式将整数填充为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些文本中,我有一系列不同长度的数字(从1到6位数字).我想通过用零填充较短的数字来均衡所有这些数字的长度.

I have a series of numbers of different lengths (varying from 1 to 6 digits) within some text. I want to equalize the lenghts of all these numbers by padding shorter numbers by zeros.

例如以下4行-

A1:11
A2:112
A3:223333
A4:1333
A5:19333
A6:4

应成为填充整数

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

我正在使用"sed"和以下合意的表达方式:

I am using "sed" and the following combersome expression:

sed -e 's/:\([0-9]\{1\}\)\>/:00000\1/' \
    -e 's/:\([0-9]\{2\}\)\>/:0000\1/' \
    -e 's/:\([0-9]\{3\}\)\>/:000\1/' \
    -e 's/:\([0-9]\{4\}\)\>/:00\1/' \
    -e 's/:\([0-9]\{5\}\)\>/:0\1/'

是否可以用比这更好的表达方式?

Is it possible to do this in a better expression than this?

推荐答案

您可以在其上填充太多零,然后仅保留最后六位数字:

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/'

结果:


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

虽然最好使用awk:

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

这篇关于是否可以使用正则表达式将整数填充为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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