shell scripts - Lesson Three Musketeers VII sed statement

sed command
  Linux text processing Three Musketeers sed
  sed Stream EDite
    as a line editor, text editing (editing in units)
    Note: sed to edit the file, but do not change the original file;

  works of sed:
    Specify a text file, in order to read the contents of a text file each line is read into the pattern space (pATTERN sPACE), text matching (regular expression) in the pattern space, the contents of the match modify (replace, delete, print, modify, , save, etc.)

  Usage:
    sed [OPTION] ... {Script-only-IF-NO-OTHER-Script} [the INPUT-File] ...
    sed [parameters] "sed own independent use format statement" [Text File]

  Common Options
    -n reject the default display
    -r specify extended regular expression
      matching IP
      1, all \ are not 2, | or
    -e Script for the while IF
    -f specify the script file
    -l length specified text wrap?
    -i edit files (do not use)

  the address delimited embodiment
    1, the direct matching value
      sed -n '5p' file
    2, d ~ step
      sed -n '1 ~ 3p' file
    3, the end of the specified line $
      sed -n '10, $ p 'document
    4, / regular /
      / regular 1 /, / n is 2 /
        Sed -n' / K \ {. 5, \} /, $ P 'ABC
        Sed -n' / \ (FD \) \ + /, + 2p 'abc? regular EDITORIAL no problem, there is a problem written on the back
        sed -n'
    5,0, addr
      addr can be a digital / $ / regular expression
      sed -n '0, / k \ . 5 {, \} / P 'ABC
    . 6, addr, + N
      Addr line arranged to, after the line N addr
      sed -n '/ fd /, + 5p' abc

  **常见命令
    p print 打印(默认在屏幕上显示出来) 建议和 -n 一起使用;
    c 替换
      sed "/aaa/c \A" a
    d 删除
      sed "/aaa/d" a
      sed "1,3d" a
    n N 读取/添加 模式匹配到的行的下一行内容,再对其进行操作
    w 保存文件内容到一个新的文件
      sed "/patthen/w 新的文件名" 原来的文件名
      sed "/k/w /tmp/aabbcc" abc
    *s* 文本内容替换,默认替换模式空间匹配到的第一项;
      语法格式: s/pattern/字符串/
        中间的 / 可以替换为任意一个特殊字符 例如:s### s@@@ s%%%%
      g 全部
      \1 \2 和正则表达式的分组相同,实现反向应用;
        指定某一个匹配项进行修改替换
      & 调用前面(pattern)匹配的内容
        sed "s/r..t/&er/g" 文件
      w
      p

  sed的高级应用
    模式空间 -- hold space"占有空间"

  练习:
    删除/boot/grub/grub.conf文件中所有空白开头的行行首的空白字符;
      sed 's/^[[:space:]]\+//g' /boot/grub/grub.conf
    删除/etc/fstab文件中所有以#开头,后面至少跟一个空白字符的行 的行首的#和空白字符;
      sed 's/^#[[:space:]]\+//g' /etc/fstab
    给定一个目录,取出其目录名
      echo "/etc/passwd" | sed 's/[^/]\+$//'
    给定一个目录,取出其文件名
      echo "/etc/passwd" | sed 's#^/.*/\(.*\)##

    /var/log/message
      sed '/[^/]\+/'

      dirname -- 取出文件路径的路径部分
      basename -- 取出文件路径的文件名部分

 

 

 

Guess you like

Origin www.cnblogs.com/zwl123456/p/11441967.html