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?

  • 1
    Maybe grep -Po 'test1?: \K\d+' < "$file" | paste -sd , -. The order would be based on where test and test1 occur in the file. – Stéphane Chazelas Jan 24 '17 at 8:32
  • 1
    (btw, ITYM grep -Po 'test... above (assuming that's GNU grep)) – Stéphane Chazelas Jan 24 '17 at 8:33
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")"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.