4

Suppose I have these two files:

1.

Locus_1 univ
Locus_2 anc
Locus_3 cat

2.

university  GO:000001
impromptu   GO:000002
advanced    GO:000003
inheritance GO:000004

I want to do a grep -f of the $2 of file #1 on file #2, but I also want to retrieve the lines of the first file and the whole line of file #2 that match $2 of file #1.

Basically, I want my output to be like this

Locus_1 univ university GO:000001
Locus_2 anc  advanced   GO:000003

How can I do this? I thought I could parse the first file line by line with a for cycle and then store the line in a variable, but I was not able to succeed.

I use a Cygwin shell for Windows.

3
  • Can you use awk? Commented May 31, 2016 at 10:48
  • @MichaelVehrs: yes, Cygwin is intended to be more or less like a Linux shell, so I can use it, as well as sed etc. Commented May 31, 2016 at 10:50
  • Are the values unique in any of the columns?
    – choroba
    Commented May 31, 2016 at 10:56

1 Answer 1

9

Save this to a file, let's say patterns.awk, then call awk -f patterns.awk patterns data, where patterns is your first file, and data the second:

NR == FNR {
    prefix[NR] = $0;
    pattern[NR] = $2;
    count++;
    next;
}

{
    for (i = 1; i <= count; i++) {
        if (index($1, pattern[i]) > 0) {
            print prefix[i] " " $0;
            next;
        }
    }
}

This works as follows: The first rule is used while we are reading the pattern file, i.e. while the total number of records equals the number of records in the file. It saves the line and the pattern to search for in two arrays and continues. The second rule is used as soon as the total number of records exceeds the number of records in the file, i.e. while we are reading the data file. It checks whether any of the patterns matches the first column of the line. If so, it prints the matching line from the pattern file, and then the matching line from the data file.

1
  • Great! That did perfectly! Can you explain me in detail what does this script do? Commented May 31, 2016 at 11:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .