【问题标题】:How to extract a substring matching a pattern from a Unix shell variable如何从 Unix shell 变量中提取与模式匹配的子字符串
【发布时间】:2010-10-27 16:29:16
【问题描述】:

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

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 命令可以做到这一点,但我真的不知道从哪里开始。

有什么建议吗?

【问题讨论】:

    标签: regex unix shell sed grep


    【解决方案1】:

    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
    

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

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

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

    【讨论】:

      【解决方案2】:

      这里有一个快速而肮脏的技巧,虽然你应该自己开始学习这些东西:

      RC=`tail -1 $test |sed 's/(返回状态 = \([0-9]\+\))/\1/'`

      【讨论】:

      • 谢谢。这就是我要问的原因:我希望看到有经验的 Unix 编码人员能够解决现实世界的问题,这样我就可以学会自己去做。所以在这种情况下,tail 命令将 $test 的最后一行传递给 sed 命令,该命令返回 \( 和 )\ 内的任何内容(假设整体模式匹配)。对吗?
      • 是的,\( 和 \) 之间的任何内容都由替换中的 \1 给出。 [0-9]\+ 表示匹配一位或多位数字。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 2018-01-18
      相关资源
      最近更新 更多