BASH shell 使用正则表达式从文件中获取值到参数中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/13337550/
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
BASH shell use regex to get value from file into a parameter
提问by Jay Gilford
I've got a file that I need to get a piece of text from using regex. We'll call the file x.txt. What I would like to do is open x.txt, extract the regex match from the file and set that into a parameter. Can anyone give me some pointers on this?
我有一个文件,我需要使用正则表达式获取一段文本。我们将调用文件x.txt. 我想要做的是 open x.txt,从文件中提取正则表达式匹配并将其设置为参数。任何人都可以给我一些指示吗?
EDIT
编辑
So in x.txtI have the following line
所以在x.txt我有以下行
$variable = '1.2.3';
I need to extract the 1.2.3from the file into my bash script to then use for a zip file
我需要1.2.3将文件从文件中提取到我的 bash 脚本中,然后用于 zip 文件
回答by vladr
Use sedto do it efficiently?in a single pass:
用sed它高效地做吗?一次通过:
var=$(sed -ne "s/\$variable *= *['\"]\([^'\"]*\)['\"] *;.*//p" file)
The above works whether your value is enclosed in single ordouble quotes.
无论您的值是用单引号还是双引号括起来,以上都适用。
Also see Can GNU Grep output a selected group?.
另请参阅GNU Grep 可以输出选定的组吗?.
$ cat dummy.txt
$bla = '1234';
$variable = '1.2.3';
blabla
$variable="hello!"; #comment
$ sed -ne "s/\$variable *= *['\"]\([^'\"]*\)['\"] *;.*//p" dummy.txt
1.2.3
hello!
$ var=$(sed -ne "s/^\$variable *= *'\([^']*\)' *;.*//p" dummy.txt)
$ echo $var
1.2.3 hello!
? or at least as efficiently as sedcan churn through data when compared to grepon your platform of choice. :)
? 或者至少sed与grep在您选择的平台上相比可以有效地处理数据。:)
回答by doubleDown
You can use the grep-chop-chop technique
您可以使用 grep-chop-chop 技术
var="$(grep -F -m 1 '$variable =' file)"; var="${var#*\'}"; var="${var%\'*}"
回答by higuaro
If all the file lines have that format ($<something> = '<value>'), the you can use cutlike this:
如果所有文件行都具有该格式 ( $<something> = '<value>'),则可以cut像这样使用:
value=$(cut -d"'" -f2 file)

