【问题标题】:Extract string from square brackets从方括号中提取字符串
【发布时间】:2014-02-24 21:28:01
【问题描述】:

我需要从这个示例字符串中获取值 myfile.ext'My message [file:myfile.ext]'

我看到similar question,但如果括号不在字符串中,则无法使字符串返回空字符串。

我需要检查字符串是否包含[file:***],并返回变量***,否则必须为空值。

【问题讨论】:

    标签: regex bash sed awk


    【解决方案1】:

    您可以为此使用grep

    $ grep -Po '(?<=\[file:)[^]]*(?=])' file
    myfile.ext
    

    这与(取决于您是从文件还是管道读取)相同:

    $ echo "'My message [file:myfile.ext]'" | grep -Po '(?<=\[file:)[^]]*(?=])'
    myfile.ext
    

    说明

    它查找在[file: 之后和下一个] 之后的字符串。要将其存储到变量中,请使用 var=$(command) 表达式:

    result=$(grep -Po '(?<=\[file:)[^]]*(?=])' file)
    

    默认为空,否则为myfile.ext

    样本

    $ cat a
    My message [file:myfile.ext
    My message [file:myfile.ext]]a]
    
    $ grep -Po '(?<=\[file:)[^]]*(?=])' a
    myfile.ext
    

    【讨论】:

    • 次要的挑剔:它看起来不像到下一个]。对于输入 My message [file:myfile.ext,您的解决方案将返回 myfile.ext
    • 我怎么没想到grep。谢谢!
    【解决方案2】:

    您可以使用 sed 的 -n 标志来禁止打印所有行,然后专门使用正则表达式中的 p 标志来打印匹配项:

    sed -n 's/\[file:\([^\]*\)]/\1/p' file
    

    【讨论】:

      【解决方案3】:

      你可以使用这个 BASH 正则表达式:

      [[ "$s" == *[* ]] && [[ "$s" =~ \[[^:]*:([^\]]+)\] ]] && echo "${BASH_REMATCH[1]}"
      myfile.ext
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-04
        • 1970-01-01
        • 2019-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-26
        相关资源
        最近更新 更多