0

I have a file looks like:

file1:

    id1 id6
    id5 id2
    id2 id3
    id6 id500

if we compare the inside of the second column with the first column, we can note that id6 and id2 exist in the second column as well as first column. But id3 and id500 exist in second column while do not in first column. I want to replace 0 for the latter as they did not appear in first column. so the output should be:

output:

id1 id6
id5 id2
id2 0
id6 0

any suggestion? I tried some commands in "join", but I did not get what I want. note that my real data is huge and this is a small example

1

A two-pass solution - in the first pass store all values from field 1 into an array a, in the second pass print each line, with the second field being set to 0 if it is not in the array a

awk 'first{a[$1]; next}; {print $1, !($2 in a)? 0: $2}' first=1 file first=0 file
-1
#/bin/perl

use strict;
use warnings;

my  %hash;
my  @array;
my( $key, $value );

while( <ARGV> )
{
    chomp;
    @array = split '\t';    
    $hash{ $array[0] } = $array[1];
}

while(( $key, $value ) = each %hash )
{
    printf "$key\t%s\n",
        exists( $hash{ $value }) ? $value : "0";
}

Not sure what "huge" means though, whatever the size of your data, that's how much this uses. Sorry if you were looking for POSIX command type solution, I've never answered on these forums before.

  • thanks. my file has 4000 rows. I tried to run your script. I got these errors:./test.perl: line 2: $'\r': command not found ./test.perl: line 3: use: command not found ./test.perl: line 3: $'\r': command not found ./test.perl: line 4: use: command not found ./test.perl: line 4: $'\r': command not found ./test.perl: line 5: $'\r': command not found ./test.perl: line 8: syntax error near unexpected token $key,' '/test.perl: line 8: my( $key, $value ); Do you know whay? – zara Aug 4 '16 at 20:37
  • looks like my PC carriage returns got into the paste. i tried to paste it without carriage returns, but i have no way of knowing it worked. sorry :( – Eric Aug 4 '16 at 20:39
  • ???? I did not understand what your mean is – zara Aug 4 '16 at 20:43
  • oh, silly me. run it as a perl script not bash. – Eric Aug 4 '16 at 20:46
  • I ran it as perl script not bash. it did not work anyways – zara Aug 4 '16 at 20:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.