【问题标题】:How to remove square brackets and any text inside?如何删除方括号和里面的任何文字?
【发布时间】:2013-07-08 09:11:25
【问题描述】:

我有一个包含方括号内的文本的文档,例如:

The fish [ate] the bird.
[This is some] text.
Here is a number [1001] and another [1201].

我需要删除方括号和括号内的所有信息,例如:

The fish  the bird.
 text.
Here is a number  and another .
  • 我试过sed -r 's/\[[+]\]//g' file.txt,但没有成功。

如何删除模式[<anything>] 中的任何内容?

【问题讨论】:

    标签: bash sed


    【解决方案1】:

    试试这个 sed 行:

    sed 's/\[[^]]*\]//g' 
    

    示例:

    kent$  echo "The fish [ate] the bird.
    [This is some] text.
    Here is a number [1001] and another [1201]."|sed 's/\[[^]]*\]//g' 
    The fish  the bird.
     text.
    Here is a number  and another .
    

    解释:

    正则表达式实际上很简单:

    \[     #match [
    [^]]*  #match any non "]" chars
    \]     #match ]
    

    原来如此

    匹配字符串,以[ 开头,然后是除] 之外的所有字符,以] 结尾

    【讨论】:

    • 肯特。 thnx 为 exp。 :)
    【解决方案2】:

    sed 's/([^])*)/替换文本/g' 在括号 () 的情况下

    【讨论】:

      猜你喜欢
      • 2022-12-17
      • 2019-03-11
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-05
      相关资源
      最近更新 更多