Search code examples
linuxbashgrepfilteringstdin

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 is easier) that appear on some 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?


Solution

  • 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 -vf <(printf "A\nB\n")
    C
    C