【问题标题】:Extract string from brackets从括号中提取字符串
【发布时间】:2011-11-04 19:05:16
【问题描述】:

我是 bash 的新手,所以这是一个很菜鸟的问题..

假设我有一个字符串:

string1 [string2] string3 string4

我想从方括号中提取string2;但括号可能在任何其他时间围绕任何其他字符串。

我将如何使用sed 等来执行此操作?谢谢!

【问题讨论】:

    标签: bash sed


    【解决方案1】:

    另一个awk:

    $ echo "string1 [string2] string3 [string4]" |
    awk -v RS=[ -v FS=] 'NR>1{print $1}' 
    string2
    string4
    

    【讨论】:

      【解决方案2】:

      这是一个 awk 示例,但我在括号上进行匹配,这也使得 -F 的工作原理更加明显。

      echo '测试 (lskdjf)' | awk -F'[()]' '{print $2}'

      【讨论】:

        【解决方案3】:

        这是使用 awk 的一种方法:

        echo "string1 [string2] string3 string4" | awk -F'[][]' '{print $2}'
        

        这个 sed 选项也有效:

        echo "string1 [string2] string3 string4" | sed 's/.*\[\([^]]*\)\].*/\1/g'
        

        以下是 sed 命令的细分:

        s/          <-- this means it should perform a substitution
        .*          <-- this means match zero or more characters
        \[          <-- this means match a literal [ character
        \(          <-- this starts saving the pattern for later use
        [^]]*       <-- this means match any character that is not a [ character
                        the outer [ and ] signify that this is a character class
                        having the ^ character as the first character in the class means "not"
        \)          <-- this closes the saving of the pattern match for later use
        \]          <-- this means match a literal ] character
        .*          <-- this means match zero or more characters
        /\1         <-- this means replace everything matched with the first saved pattern
                        (the match between "\(" and "\)" )
        /g          <-- this means the substitution is global (all occurrences on the line)
        

        【讨论】:

        • 这确实有效,但你能解释一下发生了什么吗?
        • 当然。我会在答案中添加解释。
        • @strictlyrude27 - 我还添加了一个使用 awk 的示例。它类似于公认的答案,但在我看来更干净。
        • 为什么我们需要对匹配字符串的子字符串分组的括号进行转义?另外,我认为字符类中的右方括号必须被转义,但只有在没有它的情况下才有效!我无法理解。
        【解决方案4】:

        用 -F '[delimiters]' 指定 awk 多个分隔符

        如果分隔符是方括号,则像这样将它们背靠背放置 ][

        awk -F '[][]' '{print $2}'
        

        否则你将不得不逃脱他们

        awk -F '[\\[\\]]' '{print $2}'
        

        获取括号内值的其他示例:

        echo "string1 (string2) string3" | awk -F '[()]' '{print $2}'
        echo "string1 {string2} string3" | awk -F '[{}]' '{print $2}'
        

        【讨论】:

          【解决方案5】:
          Read file in which the delimiter is square brackets:
          $ cat file
          123;abc[202];124
          125;abc[203];124
          127;abc[204];124
          
          To print the value present within the brackets:
          $ awk -F '[][]' '{print $2}' file
          202
          203
          204
          

          乍一看,上述命令中使用的分隔符可能会令人困惑。这很简单。在这种情况下将使用 2 个分隔符:一个是 [,另一个是 ]。由于分隔符本身是方括号,要放在方括号内,第一次看起来很棘手。

          注意:如果方括号是分隔符,则只能这样放置,即首先是],然后是[。使用 -F '[[]]' 之类的分隔符将给出完全不同的解释。

          参考此链接:http://www.theunixschool.com/2012/07/awk-10-examples-to-read-files-with.html

          【讨论】:

          • 谢谢。您知道如何获取 outermost 分隔符之间的文本吗?所以如果字符串是x = (b + (c - d)),那么它应该拉出b + (c - d)。谢谢。
          【解决方案6】:

          内联解决方案可能是:

          a="first \"Foo1\" and second \"Foo2\""
          echo ${a#*\"} | { read b; echo ${b%%\"*}; }
          

          你可以单行测试:

          a="first \"Foo1\" and second \"Foo2\""; echo ${a#*\"} | { read b; echo ${b%%\"*}; }
          

          输出:Foo1

          带括号的例子:

          a="first [Foo1] and second [Foo2]"
          echo ${a#*[} | { read b; echo ${b%%]*}; }
          

          一行:

          a="first [Foo1] and second [Foo2]"; echo ${a#*[} | { read b; echo ${b%%]*}; }
          

          输出:Foo1

          【讨论】:

            【解决方案7】:

            这是另一个,但它会处理多次出现,例如

            $ echo "string1 [string2] string3 [string4 string5]" | awk -vRS="]" -vFS="[" '{print $2}'
            string2
            string4 string5
            

            简单的逻辑是这样的,你在“]”上拆分并通过拆分单词找到一个“[”,然后在“[”上拆分以获得第一个字段。在 Python 中

            for item in "string1 [string2] string3 [string4 string5]".split("]"):
                if "[" in item:
                   print item.split("]")[-1]
            

            【讨论】:

              【解决方案8】:

              在纯 bash 中:

              STR="string1 [string2] string3 string4"
              STR=${STR#*[}
              STR=${STR%]*}
              echo $STR
              

              【讨论】:

              • 用这种shell操作方法是否可以得到[string2](也可以去掉括号)?
              • 是的。要获取括号内的内容,包括括号,请执行以下操作:STR="[${STR#*[}",删除括号之前的所有内容,然后是 STR="${STR%]*}]",其中删除括号后的所有内容。变量扩展删除了括号,因此您在引号内添加了一个。
              【解决方案9】:

              试试这个:

              echo $str | cut -d "[" -f2 | cut -d "]" -f1
              

              【讨论】:

              • 只是为了确保我理解这里发生了什么(同样,在 shell 脚本方面非常菜鸟:第一个 cut 将所有内容保存到 [ 的右侧,第二个将所有内容保存到]; 这两个一起给了我想要的字符串。
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2019-07-29
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-01-26
              • 2016-04-21
              相关资源
              最近更新 更多