This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Replacing Dots In File

Hi to all

I have a file like this

chr1    9992    10466    chr1    10240    10349    .    0    +    6.679490    4.52317    -1
chr1    11026    11535    .    .    .    .    .    .    .    .    .
chr1    11560    14749    .    .    .    .    .    .    .    .    .

I would like to replace dots by zeros without replacing float values that contains . any trick to do this with perl/sed or awk ?

Many thanks

Pat

shell

Why not replacing occurrences of "t." by "t0" ?

If the input contains malformatted float values, then numbers might begin with dot... i.e. " .123 "

3 answers

sed 's/\t\./\t0/g' file.txt > output.txt

output.txt is :

chr1    9992    10466   chr1    10240   10349   0   0   +   6.679490    4.52317 -1
chr1    11026   11535   0   0   0   0   0   0   0   0   0
chr1    11560   14749   0   0   0   0   0   0   0   0   0

With Perl

 perl -ne '$_ =~ s/\t\./\t0/g; print $_' file.txt > output.txt

With Awk

awk '{ gsub("\t\\.", "\t0"); print }' file.txt  > output.txt

Or to replace in-place with perl and minimal code: perl -pi~ -e 's/t./t0/g' file.txt

The other answers will change the field separator rather than preserving it. So if files have tabs vs. spaces, this could break the file. Better is to preserve the separator in the replacement text. Although that's a more complex pattern (Perl):

s/(\s)\.(\s)/${1}0${2}/g;

or

$ perl -pe 's/(\s)\.(\s)/${1}0${2}/gx;' <dat

Likely you hit the problem of using 102 which could be interpreted as backreferencing the 10th match (although Perl isn't supposed to behave that way..).

You asked for perl/sed/awk, however it's also very easy in Vim. Vim is handy for this because you can experiment with bunch of regex's and then hit Undo until you finally get what you want.

  • load the file
  • Use the regex command as follows.

    :%s/ . / 0 /g

or to preserve the separator,

:%s/\(\s\)\.\(\s\)/\10\2/g

Log in to answer this question.