Kar*_*k M 4 regex linux bash shell
字符串看起来像
str1= "the value of var1=test, the value of var2=testing, the final value of var3=testing1"
Run Code Online (Sandbox Code Playgroud)
到目前为止,我通过 IFS=',' 分割了字符串
IFS="," read -r -a final <<< "$str1"
Run Code Online (Sandbox Code Playgroud)
然后给变量赋值
var1="${final[0]#"var1="}"
Run Code Online (Sandbox Code Playgroud)
如何使用正则表达式以最短的方式分配变量值?
预期输出
var1=test
var2=testing
var3=testing1
Run Code Online (Sandbox Code Playgroud)
#!/usr/bin/env bash
str1="the value of var1=test, the value of var2=testing, the final value of var3=testing1"
re='(^|[[:space:]])([[:alpha:]][[:alnum:]]*)=([^, ]+)([, ]|$)(.*)'
remaining=$str1
while [[ $remaining =~ $re ]]; do
varname=${BASH_REMATCH[2]}
value=${BASH_REMATCH[3]}
remaining=${BASH_REMATCH[5]}
printf -v "$varname" %s "$value"
done
# show current values to demonstrate that variables were really assigned
declare -p var1 var2 var3
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为=~将正则表达式中的每个匹配组存储在变量的不同位置BASH_REMATCH,因此我们能够挑选出具有名称和值的组并执行间接赋值(printf -v varname %s "$value"stores valuein varname)。
正则表达式有相当多的内容,所以让我们逐个分解它:
(^|[[:space:]])确保我们只匹配字符串开头或前面有空格的内容。([[:alpha:]][[:alnum:]]*)=([^, ]+)仅匹配左侧为有效变量名称(一个字母,可选后跟可以是字母或数字的字符)的赋值。由于您的示例数据的值后面有逗号,因此我们知道值中不允许使用逗号,因此我们不允许将逗号和空格视为值的一部分。([, ]|$)允许变量以逗号或空格结束,或者在输入末尾结束。(.*)'匹配我们尚未处理的任何剩余内容,以便可以在循环的时间周期上针对正则表达式运行内容。