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

  • 相关阅读:
    华为云DevCloud为开发者提供高效智能的可信开发环境
    【HC资料合集】2019华为全联接大会主题资料一站式汇总,免费下载!
    在modelarts上部署mask-rcnn模型
    独立物理机和虚拟机比较有什么优势?
    .Net Core下使用MQTT协议直连IoT平台
    解惑Python模块学习,该如何着手操作...
    sar命令,linux中最为全面的性能分析工具之一
    窥探日志的秘密
    Debian 如何使用测试版更新软件包到最新的版本
    如何使用vsphere client 克隆虚拟机
  • 原文地址:https://www.cnblogs.com/sea-stream/p/14067623.html
Copyright © 2011-2022 走看看