lsyf8 发表于 2018-8-29 10:40:15

shell脚本工具之sed命令

  sed就是批处理的流编辑器,可以对来自文件或标准输入的输入流进行转换,sed通常被用作管道中的过滤器.由于sed仅仅对其输入进行一遍扫描,因此比其它交互式编辑器更加高效.
  文件内容:
  # cat sed.txt
  1
  tong
  2
  cheng
  3
  Hellow
  4
  Word
  wu han
  2 4 5
  JD
  Tao Bao
  #
  常用参数:
  -n            --只输出匹配的行
  -e            --多项编辑
  -f               --使用脚本对文件处理
  -i               --直接修改文件内容
  -r            --在脚本中使用扩展正则表达式
  1.只显示匹配的行
  # sed -n '2p' sed.txt
  tong
  # sed -n '/^J/,$p' sed.txt      --以J开头到结尾输出
  JD
  Tao Bao
  #
  2.直接修改文件内容
  # sed -i '/3/c 3.00' sed.txt
  # grep '3.00' sed.txt
  3.00
  #
  3.使用脚本名对文件处理
  # cat 1.sh
  #!/bin/sed -f
  3,5p
  # sed -n -f 1.shsed.txt
  2
  cheng
  3.00
  #
  4.对文件多项编辑
  # sed -n -e '2p' -e '4p' sed.txt
  tong
  cheng
  #
  常用命令:
  a         --在匹配字符后新增
  c         --替换
  d         --删除
  i          --插入
  p         --打印.通常与参数 sed -n 一起用
  s         --取代.通常这个 s 的动作可以搭配正则表达式。例如 1,20s/old/new/g
  5.在文件中追加内容
  # sed '/2/a\1111111111' sed.txt
  1
  tong
  2
  1111111111
  cheng
  3.00
  Hellow
  4
  Word
  wu han
  2
  1111111111
  JD
  Tao Bao
  #
  6.替换匹配的内容
  # sed '/2/c\1111111111' sed.txt
  1
  tong
  1111111111
  cheng
  3.00
  Hellow
  4
  Word
  wu han
  1111111111
  JD
  Tao Bao
  #
  7.删除文件的内容
  # sed '3,10d' sed.txt
  1
  tong
  JD
  Tao Bao
  #
  8.打印文件中的内容
  # sed -n '3,4p' sed.txt
  2
  cheng
  # sed -n '/2/,5p' sed.txt
  2
  cheng
  3.00
  2
  #
  9.将匹配的内容保存到另一个文件中
  # sed -n '3,4 w2.txt' sed.txt
  # cat 2.txt
  2
  cheng
  #

页: [1]
查看完整版本: shell脚本工具之sed命令