I have a file with a list of pattern like this




I want to grep and print my pattern in a tab delimited table (the original table is without blank line) like this:

K00001  ko00010_Glycolysis__Gluconeogenesis

K00003  ko00010_Glycolysis__Gluconeogenesis

K00005  ko00010_Glycolysis__Gluconeogenesis

K00001  ko00020_Citrate_cycle_(TCA_cycle)

K00003  ko00020_Citrate_cycle_(TCA_cycle)

K00005  ko00020_Citrate_cycle_(TCA_cycle)

to obtain this: one line with all the pattern that are in my patterns' file

  • Are you required to use grep? This would be easier with sed or awk. – Mark Plotnick Jan 21 '15 at 20:23
  • Are there blank lines in the pattern file? – Mark Plotnick Jan 21 '15 at 20:25
  • Hi, mark no there aren't blank lines in the file – Ilario Ferrocino Jan 21 '15 at 21:05

This solution uses awk. We'll pass both filenames as arguments, and use the if (FNR == NR) idiom to do something different depending on whether we're reading the first or second file. We'll use associative arrays to store the keys and the output lines.

This is the file a.awk:

# usage: awk -f a.awk keyfile1 datafile2
    FS = "\t"                               # set field separator to TAB
    if (FNR == NR) {                        # if looking at first (key) file
        k[$1]=$1                            # just save each key
    } else {                                # if looking at second file
        if ($1 in k) {                      # if first col is one that we want
            output=$1 "_" $2                # prepare output line
            if (out[$1]=="")                # if first time we've seen this key
                out[$1]=output              # store output as is
            else                            # and when we find more matches for this key
                out[$1]=out[$1] ";" output  # we append ";" and the output
END {                                       # at the end
    for (i in out)                          # print all the output lines
        print out[i]

And here is how to use it:

$ awk -f a.awk file1 file2
  • HI mark is there the possibility also to print a blank line if one more pattern are not found in file2?? – Ilario Ferrocino Jan 22 '15 at 9:18
  • @IlarioFerrocino I'm not totally sure what you mean. But, if you want a blank line for every pattern in file1 that is not matched at all in file2, change for (i in out) to for (i in k). This loops through all the keys rather than all the matched lines. So if you have key K00002 in file1 but not in file2, out["K00002"] will be "" (since it was never set) and an empty line will be printed. Is that what you need? – Mark Plotnick Jan 22 '15 at 15:06

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.