grep supports -m option to specify the maximum number of matching lines in the output.

# all input lines containing 'a' $ printf 'goal\nrate\neat\npit\n' | grep 'a' goal rate eat  # maximum of 2 matching lines $ printf 'goal\nrate\neat\npit\n' | grep -m2 'a' goal rate $ printf 'goal\nrate\neat\npit\n' | grep -m2 'pi' pit  # example with -v option $ printf 'goal\nrate\neat\npit\n' | grep -v 'e' goal pit $ printf 'goal\nrate\neat\npit\n' | grep -v -m1 'e' goal 

With multiple file input, the restriction is applied for each file separately.

$ cat table.txt  brown bread mat cake 42 blue cake mug shirt -7 yellow banana window shoes 3.14 $ printf 'goal\nrate\neat\npit\n' > ip.txt  $ grep -m1 'i' table.txt ip.txt table.txt:blue cake mug shirt -7 ip.txt:pit  # use 'cat' if you want to operate on combined input $ cat table.txt ip.txt | grep -m1 'i' blue cake mug shirt -7 $ cat table.txt ip.txt | grep -m1 'go' goal 

Video demo:


info See my CLI text processing with GNU grep and ripgrep ebook if you are interested in learning about GNU grep and ripgrep commands in more detail.