I'm trying to grep lines from a execution output with a multi-line shell variable, but I'm not quite sure how to do it for example, if I execute a file named run and the result is:
blahblah aaa
blahblah bbb
blabhblasd ccc
----------- ddd
...
blah blah ggg
and so on. And then, I have a shell variable, which is a another result from grep (and is multiline), for example $VAR holds
aaa
bbb
ggg
I want to grep this $VAR from the result of run, so I have the result
blahblah aaa
blahblah bbb
blah blah ggg
I tried something like
run | grep "VAR" but I'm not quite getting the result I want. Is there any way to grep multi-line variable from a execution output?
CodePudding user response:
$ cat file
blahblah aaa
blahblah bbb
blabhblasd ccc
----------- ddd
...
blah blah ggg
$ echo "$var"
aaa
bbb
ggg
$ cat file | awk -v var="$var" 'BEGIN{split(var,tmp); for (i in tmp) arr[tmp[i]]} $NF in arr'
blahblah aaa
blahblah bbb
blah blah ggg
Replace cat file
with run
.
CodePudding user response:
Does this do what you want?
run | grep -f <(printf '%s\n' "$var")
- It prints any line of the
run
output that matches any line in the$var
variable. - See Process Substitution in the Bash Reference Manual for an explanation of
<(printf '%s\n' "$var")
. - See the accepted, and excellent, answer to Why is printf better than echo? for an explanation of why I used
printf
instead ofecho
to output the contents of$var
. - See Correct Bash and shell script variable capitalization for an explanation of why I used
$var
instead of$VAR
.