Replacing Dots In File
3
0
Entering edit mode
12.6 years ago
Patrick ▴ 40

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 • 2.8k views
ADD COMMENT
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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

ADD REPLY
8
Entering edit mode
12.6 years ago
toni ★ 2.2k

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
ADD COMMENT
2
Entering edit mode
12.6 years ago

With Perl

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

With Awk

awk '{ gsub("\t\\.", "\t0"); print }' file.txt  > output.txt
ADD COMMENT
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode
12.6 years ago

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
ADD COMMENT

Login before adding your answer.

Traffic: 1350 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6