如何将grep输出中的值存储在变量中

rut*_*ut2 6 linux bash shell

我正在编写一个 bash 脚本,其中我必须使用正则表达式来匹配字符串,然后将输出存储在一个变量中以重用它。

这是我的脚本,

#!/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
Run Code Online (Sandbox Code Playgroud)

我尝试了很多方法,但出现错误:
./check.sh: MET-3-get-issue-id-from-branch-name: not found

如果我运行单独的 grep 命令,那么是的,它工作正常。但我无法存储输出。

我也试过:

por=$($NAME | grep -P -o -e '(?<=MET-).*?(\d+)')
por=$NAME | grep -P -o -e '(?<=MET-).*?(\d+)'
Run Code Online (Sandbox Code Playgroud)

以及许多其他类似的参考资料。

但它不起作用。任何人都可以帮我解决这个问题。我在 bash 方面没有太多经验。

谢谢你。

Arj*_*Dan 10

改变

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

por="$(echo "$NAME" | grep -P -o -e '(?<=MET-).*?(\d+)')"
Run Code Online (Sandbox Code Playgroud)

此外,您缺少一个结束双引号(可能只是一个错字,应该是NAME="MET-3-get-code-from-string"