Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have two files: one with list of names (500 entries) and other having some more information for each entry in A.txt and extra entries too.

File A.txt (each line is starting with > (fasta format) and has spaces, digits and special characters too, but in single line)

>xyz, B=123 
>abc, B=231
>mnp, B=567

File B.txt (has some particular information for each entry in A.txt in next line and has extra entries than file A)

>xyz, B=123
01010101010100101
>abc, B=231
1011110000011100000000
>mnp, B=567
10101
>opq, B=678
101010101010101001
>lmn, B=123
101010100000011

Result

>xyz, B=123
01010101010100101
>abc, B=231
1011110000011100000000
>mnp, B=567
10101

I want to grep the entries in list A.txt from list B.txt

thanks

share|improve this question
2  
If, according to your example, B has exactly 1 extra line for each line from A, you could try a simple grep -F -f A.txt -A 1 B.txt. –  jw013 Aug 24 '12 at 15:47
    
@jw013 but this giving a line -- after each group. –  Roli Aug 24 '12 at 16:06
2  
Yes that is an unavoidable side effect of grep -A. You can get rid of it by piping it to grep -v '^--$'. –  jw013 Aug 24 '12 at 16:13

1 Answer 1

Assuming that you want to print just two lines for each match, with GNU or FreeBSD grep, you can pass A.txt as a list of patterns to grep and tell it to print the line after the match. This produces extra lines with just -- between each match, you can easily remove them with an extra call to grep.

grep -A1 -Ff A.txt B.txt | grep -vx -- '--'

If the number of lines per section isn't fixed, you can use awk. First read the file containing the text to look for, then for each line in B.txt that starts a new section, either start or stop printing depending on whether the section head is in A.txt or not.

awk -v patterns_file=A.txt '
  BEGIN {
    while (getline <patterns_file) patterns_array[$0] = 1;
    close(patterns_file);
  }
  /^/ { matching = $0 in patterns_array }
  matching { print }
' B.txt
share|improve this answer
    
Nice @giles, but why would grep suffer if the number of lines changes? –  terdon Aug 26 '12 at 13:25
    
@terdon The grep method only works if all the matching sections have the same number of lines, because that's the number you need to specify on (-A). –  Gilles Aug 26 '12 at 14:46
    
@Giles Ah, ok, of course. I thought you meant it would not work if the number of records was variable. Gotcha. –  terdon Aug 26 '12 at 14:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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