Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add leading 0 in sed substitution

Tags:

sed

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

So I can use this sed substitutions:

s,\([a-z ]\+\)\([0-9]\)\([a-z ]*\),\100\2\3,
s,\([a-z ]\+\)\([0-9][0-9]\)\([a-z ]*\),\10\2\3,

But, can I make one substitution, that will do the same? Something like:

if (one digit) then two leading 0
elif (two digits) then one leading 0

Regards.

like image 695
Artur Szymczak Avatar asked Dec 20 '22 17:12

Artur Szymczak


2 Answers

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.

like image 180
Lev Levitsky Avatar answered Jan 02 '23 02:01

Lev Levitsky


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
like image 28
Birei Avatar answered Jan 02 '23 04:01

Birei