Add leading 0 in sed substitution

后端 未结 6 804
不思量自难忘°
不思量自难忘° 2021-01-13 15:47

I have input data:

foo 24
foobar 5 bar
bar foo 125

and I\'d like to have output:

foo 024
foobar 005 bar
bar foo 125
         


        
6条回答
  •  南笙
    南笙 (楼主)
    2021-01-13 16:11

    I find the following sed approach to pad an integer number with zeroes to 5 (n) digits quite straighforward:

    sed -e "s/\<\([0-9]\{1,4\}\)\>/0000\1/; s/\<0*\([0-9]\{5\}\)\>/\1/"
    
    1. If there is at least one, at most 4 (n-1) digits, add 4 (n-1) zeroes in front
    2. If there is any number of zeroes followed by 5 (n) digits after the first transformation, keep just these last 5 (n) digits

    When there happen to be more than 5 (n) digits, this approach behaves the usual way -- nothing is padded or trimmed.

    Input:

    0
    1
    12
    123
    1234
    12345
    123456
    1234567
    

    Output:

    00000
    00001
    00012
    00123
    01234
    12345
    123456
    1234567
    

提交回复
热议问题