MOHAMED
MOHAMED

Reputation: 43528

How to make filter on an output based on string lines?

I have the following output

$ mycommand
1=aaa
1=eee
12=cccc
15=bbb

And I have a string str containing:

eee
cccc

and I want to display only lines which contains string exist in the string lines

So my out put will be:

$ mycommand | use_awk_or_sed_or_any_command
1=eee
12=cccc

Upvotes: 0

Views: 1014

Answers (2)

terdon
terdon

Reputation: 3380

Say your command is echo -e "1=aaa\n1=eee\n12=cccc\n15=bbb", you could do

echo -e "1=aaa\n1=eee\n12=cccc\n15=bbb" | grep -wE "$(sed  'N;s/\n/|/' <<<"$str")"

The sed command simply replaces the newline (\n) with | which is used by grep -E (for extended regular expressions) to separate multiple patterns. This means that the grep will print lines matching either eee or cccc. The w ensures that the match is of an entire word, so that things like eeeeee will not be matched.

Upvotes: 2

choroba
choroba

Reputation: 241898

If you store the strings in a file, you can use grep with its -f option:

$ cat  search
eee
cccc

$ grep -wf search file
1=eee
12=cccc

You might also need the -F option if your strings contain special characters like ., $ etc.

Upvotes: 2

Related Questions