Question: (Closed) Find Nan Or Zero In One Column And Output Content Of The Second Column
0
gravatar for robjohn7000
5.9 years ago by
robjohn700080
United Kingdom
robjohn700080 wrote:

Hi,

I want the contents of column 2 (when NAN/0)in file1.txt to be replaced by the content of column1:

file1.txt:

file for parsing
mnot    NAN
PU1    0
PU2    ets
munt    tsu
PU3    ttsm
munt2    0

Required output:

file for parsing
mnot     mnot
PU1    PU1
PU2    ets
munt    tsu
PU3    ttsm    
munt2    munt2

my code is not giving the right output:

#!usr/bin/perl
use warnings;
use strict;
use diagnostics;

open(IN, "<", "file1.txt") or die "Can't open file for reading:$!";

open(OUT, ">", "outfile.txt") or die "Can't open file for writing:$!";

my $header = <IN>;
print OUT $header;


while (<IN>){
chomp;
my @sections = split(/\t/);
$sections[1] = 0; # Error: initialization in wrong place
$sections[2] = 0; # Error: s.o., also array index in perl starts at 0!

 if (($sections[2] eq 'NAN') || ($sections[2] == 0)) { # Error: always true because you set $sections[2] = 0!
     # Error: the first and second column would be in $section[0], $section[1]
    #print OUT $sections[1], "\t", $sections[1], "\n"; 
    print OUT "$sections[1]\n"; # Error: you commented away the correctly formatted output (minus wrong array index)
    }    
    else {
    #print OUT $sections[1], "\t", $sections[2], "\n";
            # Error: s.o.
    print OUT "$sections[2]\n"; # Error: you commented out the correctly formatted output (minus wrong array index)
    }
  }

Please help!

perl • 1.4k views
ADD COMMENTlink modified 5.9 years ago by Michael Dondrup46k • written 5.9 years ago by robjohn700080

Can you paste the incorrect output? And why are you setting sections[1] and sections[2] to 0?

ADD REPLYlink written 5.9 years ago by Damian Kao15k

That is really a very simple mistake, hint: you are overwriting whatever you read. In fact I think that this is a simple programming question which should not be answered here, there are simply too many simple mistakes, you need to learn basics about perl programming first. I'll mark the mistakes in your code anyway.

ADD REPLYlink modified 5.9 years ago • written 5.9 years ago by Michael Dondrup46k

In addition to Michael's comment, your example input lacks a header line, so you'll still get mnot NAN in the output if you actually used the functional script with the example input.

ADD REPLYlink written 5.9 years ago by Devon Ryan92k

cat file.txt | awk '{if ($2 == "NAN" || $2 == 0) print $1\t$1;else print $0}'

ADD REPLYlink written 5.9 years ago by Phil S.660
Please log in to add an answer.
The thread is closed. No new answers may be added.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 2054 users visited in the last hour