0

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
MOHAMED
  • 41,599
  • 58
  • 163
  • 268

2 Answers2

2

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.

choroba
  • 231,213
  • 25
  • 204
  • 289
  • it works if I m using files. But How I can make it work if my output is from command and the search string is a shell variable – MOHAMED May 07 '14 at 14:28
2

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.

terdon
  • 3,260
  • 5
  • 33
  • 57