Add leading 0 in sed substitution

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

    I doubt that the "if - else" logic can be incorporated in one substitution command without saving the intermediate data (length of the match for instance). It doesn't mean you can't do it easily, though. For instance:

    $ N=5
    $ sed -r ":r;s/\b[0-9]{1,$(($N-1))}\b/0&/g;tr" infile
    foo 00024
    foobar 00005 bar
    bar foo 00125
    

    It uses recursion, adding one zero to all numbers that are shorter than $N digits in a loop that ends when no more substitutions can be made. The r label basically says: try to do substitution, then goto r if found something to substitute. See more on flow control in sed here.

提交回复
热议问题