Skip to content
Advertisement

How to store value from grep output in variable

I am working on one bash script, in which I have to use the regular expression to match string and then store the output in a variable to reuse it.

here is my script,

#!/bin/sh

NAME="MET-3-get-code-from-string"
por="$($NAME | grep -P -o -e '(?<=MET-).*?(d+)')"    #this should store 3 in variable por

echo $por

I tried this many ways, but I am getting error :
./check.sh: MET-3-get-issue-id-from-branch-name: not found

if I run individual grep command then yes, it is working properly. But I am not able to store output.

I also tried :

por=$($NAME | grep -P -o -e '(?<=MET-).*?(d+)')
por=$NAME | grep -P -o -e '(?<=MET-).*?(d+)'

and many other similar references.

but it’s not working. can anyone please help me on this. I have not much experience in bash.

thank you.

Advertisement

Answer

Change

por="$($NAME | grep -P -o -e '(?<=MET-).*?(d+)')"

to

por="$(echo "$NAME" | grep -P -o -e '(?<=MET-).*?(d+)')"

Also, you are missing a closing double quote (maybe just a typo, should be NAME="MET-3-get-code-from-string")

Advertisement