Michal Kordas Michal Kordas - 29 days ago 17
Linux Question

Filter lines with the other set of lines in Bash

I have lines on my standard input

$printf "C\nB\nA\n"
C
B
A


and I want to filter out lines (or substrings or regexps- whatever easier) that appear on other standard input:

$printf "B\nA\n"
B
A


I expect just
C
when entries get filtered.

I've tried with

$printf "C\nB\nA\n" | grep -v `printf "B\nA\n"`


But then I'm getting

grep: A: No such file or directory


How can I perform filtering of standard input by lines returned by other command?

Answer

You can use grep's -f option:

Matching Control
    -f FILE, --file=FILE
          Obtain patterns from FILE, one per line.
          [...]

and use the <(command) syntax for using a command's output as the content to be used:

$ printf "C\nB\nA\nA\nC\nB" | grep -f <(printf "A\nB\n")
B
A
A
B