BASH shell use regex to get value from file into a

2019-07-20 18:13发布

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?

EDIT

So in x.txt I have the following line

$variable = '1.2.3';

I need to extract the 1.2.3 from the file into my bash script to then use for a zip file

标签: regex bash shell
3条回答
Fickle 薄情
2楼-- · 2019-07-20 18:46

You can use the grep-chop-chop technique

var="$(grep -F -m 1 '$variable =' file)"; var="${var#*\'}"; var="${var%\'*}"
查看更多
何必那么认真
3楼-- · 2019-07-20 18:52

Use sed to do it efficiently in a single pass:

var=$(sed -ne "s/\\\$variable *= *['\"]\([^'\"]*\)['\"] *;.*/\1/p" file)

The above works whether your value is enclosed in single or double quotes.

Also see Can GNU Grep output a selected group?.

$ cat dummy.txt
$bla = '1234';
$variable = '1.2.3';
blabla
$variable="hello!"; #comment

$ sed -ne "s/\\\$variable *= *['\"]\([^'\"]*\)['\"] *;.*/\1/p" dummy.txt
1.2.3
hello!

$ var=$(sed -ne "s/^\\\$variable *= *'\([^']*\)' *;.*/\1/p" dummy.txt)

$ echo $var
1.2.3 hello!

† or at least as efficiently as sed can churn through data when compared to grep on your platform of choice. :)

查看更多
贼婆χ
4楼-- · 2019-07-20 19:01

If all the file lines have that format ($<something> = '<value>'), the you can use cut like this:

value=$(cut -d"'" -f2 file)
查看更多
登录 后发表回答