Sed命令基本语法(一)

Sed命令基本语法(一)

学习目标

Sed工作流

Sed命令基本语法

1、 sed的工作流程

sed的工作流程分为以下几步

                       

 

流程图解说:首先读一行存放在模式空间(pattern space);

                  其次从模式空间取得该内容,并且对命令进行一个解析;

                  然后把模式空间的内容进行清空,并且输出来;

            最后反复一直读;

2、 sed命令的基本语法

(1)     sed命令的格式

sed[options]{sed-commands}{input-file}

(2) sed的p命令与-n选项(print, --quiet)

sed ‘p’  test.txt  这样会每行输出两次;(读入模式空间输出一次,清空模式空间再输出一次)

sed –n ‘p’ test.txt   加上-n与cat命令达到一样的效果;只会输出模式空间的内容 ;

 

sed –n ‘1 p’ test.txt  只打印第一行;

 

sed –n ‘1,3 p’ test.txt  打印1~3行;

 

sed –n ‘/hello/p’ test.txt  打印hello 所在行;

sed –n ‘/hello/,/hello1/p’ test.txt  打印hello 至hello1所在行;

sed –n ‘/^hello/ p’ test.txt 打印hello开头的行;(正则表达式)

sed –n ‘/hello$/ p’ test.txt  打印hello结尾的行;(正则表达式)

sed –n ‘ /^[0-9] \{3\}/ p’ test.txt 打印数字重复3次的内容;

sed –n ‘1~2 p’ test.txt   每隔一行(2-1=1)打印一次;

(3)sed的d命令(delete);和p命令类似;

sed ‘/103/  d’  test.txt  删除模式空间103所在的行;文本文件(test.txt)里面的内容不变;

(4)更多sed选项

       -f 从文件中读入命令

        Sed –f cmd.sed test.txt  新建cmd.sed命令文件,文件内容如下: /hello/ p

     可以在命令文件中写入多个命令;

       -e 选项执行多个命令

    sed –n  -e  ‘/hello/  p’ –e ‘/hello1/ p’ test.txt 打印hello和hello1所在的行;

 

posted @ 2016-05-04 12:28  Bright-Ho~蜗牛~  阅读(606)  评论(0编辑  收藏  举报