Add lead 0 in sed replacement

I have input:

foo 24 foobar 5 bar bar foo 125 

and I would like to have the conclusion:

 foo 024 foobar 005 bar bar foo 125 

Therefore, I can use these sed substitutions:

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

But can I make one replacement that will do the same? Sort of:

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

Sincerely.

+4
source share
6 answers

I doubt that the if-else logic can be included in a single substitution command without storing intermediate data (such as match lengths). This does not mean that you cannot do it easily. 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 the $N digits in the loop, which ends when no replacements can be made. The r label basically says: try wildcard, then goto r if you find something to replace. See sed here for more on flow control.

+4
source

Use two substitution commands: the first will look for one digit and insert two zeros at once, and the second will look for a number with two digits and insert one zero before this. GNU sed necessary because I use the word boundary command to find numbers ( \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 infile :

 foo 24 9 foo 645 bar 5 bar bar foo 125 

Run the previous command with the following output:

 foo 024 009 foo 645 bar 005 bar bar foo 125 
+1
source

It seems that you have sed options, here is one way with awk :

 BEGIN { RS="[ \n]"; ORS=OFS="" } /^[0-9]+$/ { $0 = sprintf("%03d", $0) } { print $0, RT } 
0
source

This may 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 eyes:

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

I find the following sed approach to fill an integer from zero to 5 (n) digits is pretty simple:

 sed -e "s/\<\([0-9]\{1,4\}\)\>/0000\1/; s/\<0*\([0-9]\{5\}\)\>/\1/" 
  1. If there is at least one, maximum 4 (n-1) digits, add 4 (n-1) zeros before
  2. If after the first conversion there are any number of zeros followed by 5 (n) digits, leave only these last 5 (n) digits

When it happens that there are more than 5 (n) digits, this approach behaves in the usual way - nothing is complemented or cropped.

Input data:

 0 1 12 123 1234 12345 123456 1234567 

Output:

 00000 00001 00012 00123 01234 12345 123456 1234567 
0
source

First add the maximum number of leading zeros, and then take this number of characters from the end:

 echo 55 | sed -e 's:^:0000000:' -e 's:0\+\(.\{8\}\)$:\1:' 00000055 
0
source

All Articles