4

I need to parse drug names from Medline abstracts. I was hoping to do this by getting outputs from grep -wf and grep -owf then using paste, but the outputs do not correspond, because grep -owf creates an output for each match, even if it is in the same line.

Pattern file:

DrugA
DrugB
DrugC
DrugD

File to parse:

In our study, DrugA and DrugB were found to be effective.  DrugA was more effective than DrugB.
In our study, DrugC was found to be effective
In our study, DrugX was found to be effective

Desired output:

DrugA    In our study, DrugA and DrugB were found to be effective. DrugA was more effective.
DrugB    In our study, DrugA and DrugB were found to be effective. DrugA was more effective.
DrugC    In our study, DrugC was found to be effective
  • /DrugC/ will not match the string Drug C. You'd have to probably massage the drug names in your list of patterns to match to include optional spaces (aka "Passive Groups"). – DopeGhoti Dec 29 '16 at 21:23
  • Sorry @DopeGhoti, should have been DrugC throughout. Now corrected – Nasir Dec 29 '16 at 21:35
  • 1
    Maybe you just need to drop the -o? – Jeff Schaller Dec 29 '16 at 21:36
2

It's not strictly grep alone, but this does the trick:

while IFS= read -r pattern; do
    grep "$pattern" input | awk -v drug="$pattern" 'BEGIN {OFS="\t"} { print drug,$0}'
done < "patterns"
3

An awk way perhaps?

awk '
    NR == FNR {
        a[$0] = 1
        n = length($0)
        w = n > w ? n : w
        next
    }
    {
        for (i in a)
            if ($0 ~ i)
                printf "%-* s %s\n", w, i, $0
    } 
' pattern_file.txt data_file.txt
2

A sed solution:

sed 's|.*|/&/{h;s/^/&\\t/p;g}|' pattern_file | sed -nf - input

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.