rut2 rut2 - 1 year ago 113
Bash Question

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,


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 :

./ 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.

Answer Source


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


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")

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download