Add leading 0 in sed substitution

后端 未结 6 849
不思量自难忘°
不思量自难忘° 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:10

    This might work for you (GNU sed):

    echo '1.23 12,345 1 12 123 1234 1' | 
    sed 's/\(^\|\s\)\([0-9]\(\s\|$\)\)/\100\2/g;s/\(^\|\s\)\([0-9][0-9]\(\s\|$\)\)/\10\2/g' 
    1.23 12,345 001 012 123 1234 001
    

    or perhaps a little easier on the eye:

    sed -r 's/(^|\s)([0-9](\s|$))/\100\2/g;s/(^|\s)([0-9][0-9](\s|$))/\10\2/g'
    

提交回复
热议问题