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

前端 未结 2 1773
时光取名叫无心
时光取名叫无心 2020-12-05 14:23

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

相关标签:
2条回答
  • 2020-12-05 14:32

    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
    
    0 讨论(0)
  • 2020-12-05 14:43

    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) }'
    
    0 讨论(0)
提交回复
热议问题