sed命令详解

Table of Contents
一、简介
    sed命令是著名的Linux系统流编辑器,具有强大的文本处理功能,和grep、awk一并称为Linux下的三大文本处理工具。
 
 
二、基本用法
 
sed [OPTION]... {script-only-if-no-other-script} [input-file]...
 
option :
        -r, --regexp-extended
 
              use extended regular expressions in the script.
 
 
        -n, --quiet, --silent
 
              suppress automatic printing of pattern space
 
       -e script, --expression=script
 
              add the script to the commands to be executed
 
       -f script-file, --file=script-file
 
              add the contents of script-file to the commands to be executed
 
       -i[SUFFIX], --in-place[=SUFFIX]
 
              edit files in place (makes backup if extension supplied).  The default operation mode is to  break  symbolic  and  hard  links.
              This can be changed with --follow-symlinks and --copy.
 
 
Address :
1  startline,endline
    e.g   1,33
    $  最后一行
2  /regexp/
    /^root$/
3  /pattern_1/,/pattern_2/
    第一次被pattern1匹配到的行开始,至第二次被pattern2匹配到的行结束,这中间的所有行
4  LineNumber
    指定的行
5  startline, +N
    从startline开始向后的N行
 
Command :
                d : 删除符合条件的行
                p:打印符合条件的行
                a\string  在指定行后追加新行,内容为string
                    \n  可以换行
                i\string  在指定的行前面添加新行,内容为string
                r file  将指定的文件内容添加至符合条件的行处
                w file  将指定范围内的行另存至指定文件中
                s/pattern/string/  修饰符  查找并替换,默认只替换每行中第一次被模式匹配到的字符串
                        修饰符
                        g  全局替换
                        i   忽略大小写
                 s/// : s###  ,   s@@@
 
 
 
三、实战练习
 
已知文本文件test的内容如下:
 
# jjj
 
 
         #   like love like
  #  love like rlike #
  #  love like rlike #
  #  love like rlike #
  #  love like rlike #
  #  love like rlike #
 
id:3:initdefault
 
#kkkkkkk
 
1    删除文件test中行首的空白符
    sed -r 's/^[[:space:]]+//g' test
 
2    替换文件中id:3:initdefault一行的数字为5
    sed 's/\(id:\)[0-9]\(:initdefault\)/\15\3/g' test
 
3    删除test文件中的空白行
    sed '/^$/d' test
 
4    删除test文件中开头的#号
    sed 's/^#//' test
 
5    删除test文件中开头的#号及后面的空白字符,但要求#后面必须有空白字符
    sed 's/^\(#[[:space:]]\{1,\}\)*//g' test
 
6    删除test文件中以空白字符后面跟#的行中的开头的空白字符和#
    sed 's/^\([[:space:]]\{1,\}\)#//g' test
或sed -r 's/^#[[:space:]]+\)*//g' test
 
7    取出一个文件路径的目录名称,后向引用的例子
    echo "/etc/passwd" | sed -r 's@^(/.*/)[^/]+/?@\1/g'