如何从Unix shell变量中提取与模式匹配的子字符串

Joh*_*ant 4 regex unix shell grep sed

我是Unix shell脚本的新手.这是我的问题.我用过这个脚本......

isql -S$server -D$database -U$userID -P$password << EOF > $test
exec MY_STORED_PROC
go
EOF

echo $test
Run Code Online (Sandbox Code Playgroud)

要生成此结果......

Msg 257, Level 16, State 1:
Server 'MY_SERVER', Procedure 'MY_STORED_PROC':
Implicit conversion from datatype 'VARCHAR' to 'NUMERIC' is not allowed.  Use
the CONVERT function to run this query.
(1 row affected)
(return status = 257)
Run Code Online (Sandbox Code Playgroud)

我想提取"257"并将其粘贴到另一个变量中,而不是回显isql输出,所以我可以从脚本中返回257.我在想某种sed或grep命令可以做到这一点,但我真的不知道从哪里开始.

有什么建议?

fma*_*arc 13

bash可以从shell变量的内容中删除部分.

${parameter#pattern}返回$ parameter的值,而不包含匹配开头的部分pattern.

${parameter%pattern}返回$ parameter的值,而不包含匹配结尾的部分pattern.

我想有更好的方法可以做到这一点,但这应该有效.所以你可以将它组合成:

% strip the part before the value:
test=${test#Msg }
% strip the part after the value:
test=${test%, Level*}
echo $test
Run Code Online (Sandbox Code Playgroud)

如果您对该(return status = xxx)部分感兴趣,那将是:

result=${test#*(result status = }
result=${result%)*}
echo $result
Run Code Online (Sandbox Code Playgroud)

bash联机帮助页的相关部分是"参数扩展".