Skip to main content
4 of 4
Rollback to Revision 2
AdminBee
  • 23.6k
  • 25
  • 55
  • 77

grep of output a previous grep

Is it possible to use the multi-line output of a grep run of one file as patterns for use with a subsequent second grep run on another file?

Example:

  • content of file1.txt
    2 blue
    1 red 
    1 green
    2 black
    2 orange
    
  • content of file2.txt
    2 blue triangle
    2 blue circle
    3 blue triangle
    2 red triangle
    3 green circle
    4 red square
    2 orange circle
    2 brown circle
    
  • Result of first grep:
    $ grep 2 file1.txt 
    
    2 blue 
    2 black
    2 orange
    

Now, I am looking for a command that implements something like

grep <PREVIOUS OUTPUT> file2.txt

that would find all lines in file2.txt that start with one of the lines produced by the grep run on file1.txt, so the desired result is:

2 blue triangle
2 blue circle
2 orange circle