zoukankan      html  css  js  c++  java
  • shell sed 字符串替换

    content

    macname@localhost Desktop % 
    macname@localhost Desktop % cat ddd
    This is a test of the test script.
    This is the second test of the test script.
    macname@localhost Desktop %

    #在行中替换文本

    macname@localhost Desktop % sed 's/test/trial/' ddd
    This is a trial of the test script.
    This is the second trial of the test script.
    macname@localhost Desktop %

    #指定sed编辑器用新文本替换第几处模式匹配的地方

    macname@localhost Desktop % 
    macname@localhost Desktop % sed 's/test/trial/2' ddd
    This is a test of the trial script.
    This is the second test of the trial script.
    macname@localhost Desktop %

    将替换标记指定为2的结果就是:sed编辑器只替换每行中第二次出现的匹配模式。
    g替换标 记使你能替换文本中匹配模式所匹配的每处地方

    macname@localhost Desktop % 
    macname@localhost Desktop % sed 's/test/trial/g' ddd
    This is a trial of the trial script.
    This is the second trial of the trial script.
    macname@localhost Desktop %


    p替换标记会打印与替换命令中指定的模式匹配的行。这通常会和sed的-n选项一起使用。
    -n选项将禁止sed编辑器输出。但p替换标记会输出修改过的行。将二者配合使用的效果就是 只输出被替换命令修改过的行

    macname@localhost Desktop % cat ddd
    This is a test of the test script.
    This is the second test of the test script.
    Dededede
    Hahahahhahahaah
    macname@localhost Desktop % 
    macname@localhost Desktop % sed -n 's/test/trial/p' ddd
    This is a trial of the test script.
    This is the second trial of the test script.
    macname@localhost Desktop %


    w替换标记会产生同样的输出,不过会将输出保存到指定文件中

    macname@localhost Desktop % cat ddd
    This is a test of the test script.
    This is the second test of the test script.
    Dededede
    Hahahahhahahaah
    macname@localhost Desktop % sed 's/test/trial/w test.txt' ddd
    This is a trial of the test script.
    This is the second trial of the test script.
    Dededede
    Hahahahhahahaah
    macname@localhost Desktop % cat test.txt
    This is a trial of the test script.
    This is the second trial of the test script.
    macname@localhost Desktop %


    sed编辑器允许选择其他字符来作为替换命令中的字符串分隔符,这里感叹号被用作字符串分隔符

    macname@localhost Desktop % cat ddd
    This is a test of the test script.
    This is the second test of the test script.
    Dededede
    Hahahahhahahaah
    macname@localhost Desktop % 
    macname@localhost Desktop % sed -n 's!test!trial!p' ddd
    This is a trial of the test script.
    This is the second trial of the test script.
    macname@localhost Desktop %

    在这个例子中,感叹号被用作字符串分隔符,这样路径名就更容易阅读和理解了。

    macname@localhost Desktop % 
    macname@localhost Desktop % sed 's!/bin/bash!/bin/csh!' /etc/passwd

  • 相关阅读:
    第二章:Java内存区域
    第六章:内核数据结构
    第十章:内核同步方法
    第九章:内核同步介绍
    第九章:zookeeper内部原理
    第三章:开始使用zookeeper的API
    第二章:了解zookeeper
    【观点】健康的心智是中国未来最大的生产力
    【流程管理分享】人事不分,问题不断
    为什么中国人勤劳而不富裕?为什么宋朝富裕而不强大?
  • 原文地址:https://www.cnblogs.com/sea-stream/p/14067623.html
Copyright © 2011-2022 走看看