【问题标题】:Replace substring with sed用 sed 替换子字符串
【发布时间】:2012-12-21 02:36:28
【问题描述】:

我有一个这样的字符串:

test:blabla

对于 sed,我想将 ':' 后面的内容替换为其他内容。

我可以设法替换一个单词,但不能替换 ':' 之后的那个。我在互联网上搜索了答案,但没有找到任何答案。

有什么帮助吗?

【问题讨论】:

    标签: shell sed sh


    【解决方案1】:

    使用:sed 's/:.*/:replaceword/'

    $ echo test:blabla | sed 's/:.*/:replaceword/'
    test:replaceword
    

    或者对于你只想替换:后面的单词的情况test test:blabla test使用sed 's/:[^ ]*/:replaceword/'

    $ echo "test test:blabla test" | sed 's/:[^ ]*/:replaceword/'
    test test:replaceword test
    
    # Use the g flag for multiple matches on a line
    $ echo "test test:blabla test test:blah2" | sed 's/:[^ ]*/:replaceword/g'
    test test:replaceword test test:replaceword
    

    【讨论】:

      【解决方案2】:
      > echo $SER2
      test:blabla
      > echo $SER2 | sed 's/\([^:]*:\).*/\1replace/g'
      test:replace
      >
      

      【讨论】:

        猜你喜欢
        • 2020-07-28
        • 2020-03-13
        • 1970-01-01
        • 2021-03-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-17
        相关资源
        最近更新 更多