代码之家  ›  专栏  ›  技术社区  ›  John M Gant aman_novice

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

  •  4
  • John M Gant aman_novice  · 技术社区  · 16 年前

    我对unixshell脚本比较陌生。这是我的问题。我用过这个脚本。。。

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

    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)
    

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

    有什么建议吗?

    2 回复  |  直到 16 年前
        1
  •  13
  •   fmarc    12 年前

    bash可以从shell变量的内容中剥离部分。

    ${parameter#pattern} 返回$parameter的值,该值开头没有匹配的部分 pattern .

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

    我想有更好的办法,但这应该行得通。 因此,您可以将其组合为:

    % strip the part before the value:
    test=${test#Msg }
    % strip the part after the value:
    test=${test%, Level*}
    echo $test
    

    如果你对 (return status = xxx) 第二部分是:

    result=${test#*(result status = }
    result=${result%)*}
    echo $result
    

    bash手册页的相关部分是“参数扩展”。

        2
  •  2
  •   Nikolai Fetissov    16 年前

    RC=`tail -1 $test |sed 's/(return status = \([0-9]\+\))/\1/'`