【问题标题】:Replacing from match to end-of-line从匹配替换到行尾
【发布时间】:2011-06-30 03:35:49
【问题描述】:

这应该非常简单,但我无法让它工作。我只想使用 sed 将一个字符串替换为行尾。例如,如果我有以下数据文件:

   one  two  three  five
   four two  five five six
   six  one  two seven four

我想从单词“two”到行尾替换为单词“BLAH”,并以输出结尾:

   one BLAH
   four BLAH
   six one BLAH

不就是这样吗:

   sed -e 's/two,$/BLAH/g'

我不是最擅长正则表达式,也许这就是问题所在

【问题讨论】:

    标签: regex sed


    【解决方案1】:

    这应该做你想做的:

    sed 's/two.*/BLAH/'

    $ echo "   one  two  three  five
    >    four two  five five six
    >    six  one  two seven four" | sed 's/two.*/BLAH/'
       one  BLAH
       four BLAH
       six  one  BLAH
    

    $ 是不必要的,因为 .* 无论如何都会在行尾结束,而最后的 g 是不必要的,因为您的第一个匹配将是第一个 two 到末尾行。

    【讨论】:

      【解决方案2】:

      用这个,两个<anything any number of times><end of line>

      's/two.*$/BLAH/g'
      

      【讨论】:

        【解决方案3】:

        awk

        awk '{gsub(/two.*/,"")}1' file
        

        红宝石

        ruby -ne 'print $_.gsub(/two.*/,"")' file
        

        【讨论】:

          猜你喜欢
          • 2019-02-21
          • 1970-01-01
          • 1970-01-01
          • 2022-11-11
          • 1970-01-01
          • 1970-01-01
          • 2013-12-26
          • 1970-01-01
          • 2022-01-20
          相关资源
          最近更新 更多