10.3.3 查找替换

使用s命令可将查找到的匹配文本内容替换为新的文本。


  1. #s 命令用于替换文本,本例中使用LINE

  2. 替换line

  3. #

  4. 请注意每一行只有第一个line 被替换了,默认情况下只替换第一次匹配到的内容

  5. [root@localhost ~]# sed 's/line/LINE/' Sed.txt this is LINE 1, this is First line this is LINE 2, the Second line, Empty line followed this is LINE 4, this is Third line this is LINE 5, this is Fifth line #

  6. 要想每行最多匹配2

  7. line

  8. ,并改为LINE

  9. ,可用如下方式

  10. #

  11. 注意到第2

  12. 行中有3

  13. line

  14. ,前两个被替换了,第三个没有变化

  15. [root@localhost ~]# sed 's/line/LINE/2' Sed.txt this is line 1, this is First LINE

  16. this is line 2, the Second LINE, Empty line followed this is line 4, this is Third LINE

  17. this is line 5, this is Fifth LINE

  18. #s

  19. 命令利用g

  20. 选项,可以完成所有匹配值的替换

  21. [root@localhost ~]# sed 's/line/LINE/g' Sed.txt this is LINE 1, this is First LINE

  22. this is LINE 2, the Second LINE, Empty LINE followed this is LINE 4, this is Third LINE

  23. this is LINE 5, this is Fifth LINE

  24. #

  25. 只替换开头的this that

  26. [root@localhost ~]# sed 's/^this/that/' Sed.txt that is line 1, this is First line that is line 2, the Second line, Empty line followed that is line 4, this is Third line that is line 5, this is Fifth line