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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40519902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:22:50  来源:igfitidea点击:

How to store value from grep output in variable

linuxbashshell

提问by rut2

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.

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

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

我尝试了很多方法,但出现错误:
./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.

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

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.

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

thank you.

谢谢你。

采纳答案by Arjun Mathew Dan

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

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