4

Basically I have below scenario e.g.

  1. grep 'test: \K(\d+)' $file => 15
  2. grep 'test1: \K(\d+)' $file => 20

Is there any way to store result of both commands into a variable like with comma as separator,

Test="grep 'test: \K(\d+)' $file;grep 'test1: \K(\d+)' $file"

Answer=eval $Test

Expected output: 15,20?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Rocky86
  • 651

2 Answers2

8

Yes, you can do that by using Command substitution:

Test="$(grep 'test: \K(\d+)' $file),$(grep 'test1: \K(\d+)' $file)"

The variable=$(..) called Command substitution and it's means nothing more but to run a shell command and store its output to a variable or display back using echo command. For example, display date and time:

echo "Today is $(date)"

and for store it to a variable:

SERVERNAME="$(hostname)"

you can concatenate to output:

echo "$(hostname),$(date)"

the result will be:

yourhostname,Tue Jan 24 09:56:32 EET 2017
0

To put the output of a command into a variable, use command substitution, that's exactly what it's for. Using eval cannot help (even if you were using it correctly, which you aren't).

Test="$(grep 'test: \K(\d+)' "$file"; grep 'test1: \K(\d+)' "$file")"

The output is two numbers (assuming that each of the patterns matches exactly once) separated by a newline. The reason they are separated by a newline is that grep outputs lines (like any other tool), and a line always ends with a newline character. The first grep prints 15 with a newline at the end, the second grep prints 20 with a newline at the end, and then the command substitution strips the newline(s) at the end. If you want a comma as the separator, use two command substitutions, and include the comma in between:

Test="$(grep 'test: \K(\d+)' "$file"),$(grep 'test1: \K(\d+)' "$file")"