Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
>abc, B=231
>mnp, B=567
>opq, B=678
>lmn, B=123


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

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


share|improve this question
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
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
up vote 4 down vote accepted

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 '
    while (getline <patterns_file) patterns_array[$0] = 1;
  /^/ { 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


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.