Add leading 0 in sed substitution

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

    Use two substitute commands: the first one will search for one digit and will insert two zeroes just before, and the second one will search for a number with two digits and will insert one zero just before. GNU sed is needed because I use the word boundary command to search for digits (\b).

    sed -e 's/\b[0-9]\b/00&/g; s/\b[0-9]\{2\}\b/0&/g' infile
    

    EDIT to add a test:

    Content of infile:

    foo 24 9
    foo 645 bar 5 bar
    bar foo 125
    

    Run previous command with following output:

    foo 024 009
    foo 645 bar 005 bar
    bar foo 125
    

提交回复
热议问题