I have a file with text and numbers in it like this
had   hdb   hdc
1.5   -.3   4.6
2.0   7.1   .09
.17   7.4   8.9
So for those numbers without a leading zero before decimal points, how can I add those zeros back with a simple one line command?
I have a file with text and numbers in it like this
had   hdb   hdc
1.5   -.3   4.6
2.0   7.1   .09
.17   7.4   8.9
So for those numbers without a leading zero before decimal points, how can I add those zeros back with a simple one line command?
 
    
     
    
    One option would be to use a sed substitution:
sed -E 's/(^|[^0-9])\./\10./g' file
Match (and capture) the start of the line or any non-digit followed by a .. Replace with the captured part \1 followed by 0.:
had   hdb   hdc
1.5   -0.3   4.6
2.0   7.1   0.09
0.17   7.4   8.9
 
    
    Search for a decimal proceeded by a non-number and followed by a number globally (the g flag), and replace it with that same pattern (\2 part) but with a 0 in front of the decimal.
sed 's/\([^0-9]\|^\)\(\.[0-9]*\)/\10\2/g' input.txt
Output:
had   hdb   hdc
1.5   -0.3   4.6
2.0   7.1   0.09
0.17   7.4   8.9
 
    
    With perl which supports lookarounds
$ perl -pe 's/(?<!\d)\./0./g' file 
had   hdb   hdc
1.5   -0.3   4.6
2.0   7.1   0.09
0.17   7.4   8.9
(?<!\d)\. match . which is not preceded by a digit0. for such matches, add a 0 before 
    
    As the awk printf modifiers are a mystery to me every time I use them, I just had to give it a go:
$ awk '
{
    for (i=1; i<=NF; i++)                          # for each field
        if($i ~ /[-\.0-9]+/)                       # if looks like a number
            printf "%5.2g%s", $i, (i<NF?OFS:ORS);  # print one way
        else 
            printf "%5s%s", $i, (i<NF?OFS:ORS)     # else the other way
}' file
  had   hdb   hdc
  1.5  -0.3   4.6
    2   7.1  0.09
 0.17   7.4   8.9
The only visible flaw is 2.0 getting evened to 2 (3rd record, 1st field). Is there a way to fix that?
 
    
    Perl version:
perl -pe 's/([\d\.-]+)/$1 < 1 ? $1 + 0 : $1/ge' file
Output:
had   hdb   hdc
1.5   -0.3   4.6
2.0   7.1   0.09
0.17   7.4   8.9
 
    
    Why doesn't the first sub work on .09?
awk '{sub(/^\./,"0.")sub(/-/,"-0")sub(/\.09/,"0.09")}1' file
had   hdb   hdc
1.5   -0.3   4.6
2.0   7.1   0.09
0.17   7.4   8.9
