0

Imagine that input pipe is a list of words like "foo", "bar" in CSV format.

And then there's this file or something and I'd like to test whether it contains "foo" (1) or "bar" (2) so something like:

echo "foo\nbar" | grep input.txt $0

and I'd like to get merged result of these 2 grep operations in the output:

grep "foo" input.txt
grep "bar" input.txt

Example:

input.txt = "foo1\nfoo2n\bar\n123"
output = "foo1\nfoo2n\bar\n"

I don't care how many times it runs if it does search for all the arguments.

0

1 Answer 1

2

You can use the -f flag that reads from a file, giving /dev/stdin as the filename, which makes it point to standard input.

printf '%s\n' "foo" "bar" | grep -f /dev/stdin input.txt 

Some implementations of Grep also allow for a hyphen - to represent standard input.

I have also used Printf (which prints "foo" and "bar" separated by newlines) because it is more portable than Echo. Bash Echo would require the -e flag to interpret \n as a newline character.

3
  • Thanks! Will it run grep 2 times separately for "foo" and "bar"? I'm sorry if it wasn't clear from the question.
    – Serge Vu
    Oct 2, 2020 at 12:59
  • You are welcome. Grep only runs once, but it matches lines with "foo" and lines with "bar". The difference to running 2 Greps, one for "foo" and other for "bar", is that there will be no duplicate lines. From your edit now, it seems that you want it to run twice?
    – Quasímodo
    Oct 2, 2020 at 13:01
  • Let's try to figure it out: What is your Grep? Can you show us grep --version? Does replace -f - by -f /dev/stdin work?
    – Quasímodo
    Oct 2, 2020 at 13:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .