代码之家  ›  专栏  ›  技术社区  ›  Brady Maf

如何从shell脚本中的字符串中获取特定字符串

  •  0
  • Brady Maf  · 技术社区  · 2 年前

    我在绳子下面,我想 2563 从下面的字符串中使用shell脚本。

    你能帮我查一下电话号码吗 request id

    "requested producer access with request id 2563 to product exampledomain.test-dev.test.nonprod.com for user : test-user on product test-product-validation-required"
    
    2 回复  |  直到 2 年前
        1
  •  2
  •   Benjamin W. Loc Tran    2 年前

    假设字符串存储在变量中 $s .

    这是唯一的号码吗?然后

    grep -Eo '[[:digit:]]+' <<< "$s"
    

    会有用的。

    或者使用Bash正则表达式:

    re='request id ([[:digit:]]+)'
    [[ $s =~ $re ]]
    echo "${BASH_REMATCH[1]}"
    
        2
  •  1
  •   kj-crypto    2 年前

    你需要使用 grep -oE '[0-9]*' 在字符串上,比如:

    data="requested producer access with request id 2563 to product exampledomain.test-dev.test.nonprod.com for user : test-user on product test-product-validation-required"
    
    echo $data | grep -oE '[0-9]*'
    

    输出: 2563

        3
  •  0
  •   ufopilot    2 年前
    id=$(awk -F" id | to " '{gsub(/ /,"", $2); print $2}' <<<$string)