gpt4 book ai didi

linux - 基于正则表达式从字符串中获取值

转载 作者:太空宇宙 更新时间:2023-11-04 09:20:34 26 4
gpt4 key购买 nike

我有一个我正在尝试学习的 bash 脚本。我有一个 sql 文件,里面有:

create user myuser with password 'mypassword';

我想使用 sed 并将密码值存储在一个 bash 变量中,将密码存储在另一个 bash 变量中。我正在学习的脚本有:

USERNAME := $(shell sed -n \
"s/^create user \(\S\+\) with password '\(\S\+\)';$$/\1/p" \
createdb.sql)
PASSWORD := $(shell sed -n \
"s/^create user \(\S\+\) with password '\(\S\+\)';$$/\2/p" \
createdb.sql)

无论我怎么尝试,正则表达式都不匹配。我的部分问题是我不了解 sed 的基础知识。如何获取字符串部分的值?

最佳答案

不要为此使用sed;使用 bash 的内置正则表达式支持。

str="create user myuser with password 'mypassword';"
regex='create user (.*) with password (.*);'
if [[ $str =~ $regex ]]; then
username=${BASH_REMATCH[1]}
password=${BASH_REMATCH[2]}
fi

至于如何首先获取适当的行,请使用 grep:

str=$(grep "create user" createddb.sql)

关于linux - 基于正则表达式从字符串中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42419970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com