Linux文本处理三剑客之sed详解
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
一.sed概述
1>.sed工具简介
什么是sed: sed是Stream Editor的简写名称,它是流或者批量非交互式(non-intercative)的编辑工具。 sed的工作原理: sed是一种流编辑器(Stream EDitor),它一次处理一行内容。处理时,把当前处理的行存储在临时缓冲区中,称为"模式空间"(pattern space),接着用sed命令处理缓冲区中的内容,处理完成后,把缓冲区的内容送往屏幕。然后读入下行,执行下一个循环。 如果没有使诸如"D"的特殊命令,那会在两个循环之间清空模式空间,但不会清空保留空间。这样不断重复,直到文件末尾。文件内容并没有改变,除非你使用重定向存储输出。 sed功能: 主要用来自动编辑一个或多个文件,简化对文件的反复操作,编写转换程序等 博主推荐阅读: http://www.gnu.org/software/sed/manual/sed.html
2>.sed常用选项
[root@node101.yinzhengjie.org.cn ~]# sed --help Usage: sed [OPTION]... {script-only-if-no-other-script} [input-file]... -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 --follow-symlinks follow symlinks when processing in place -i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if SUFFIX supplied) -c, --copy use copy instead of rename when shuffling files in -i mode -b, --binary does nothing; for compatibility with WIN32/CYGWIN/MSDOS/EMX ( open files in binary mode (CR+LFs are not treated specially)) -l N, --line-length=N specify the desired line-wrap length for the `l' command --posix disable all GNU extensions. -r, --regexp-extended use extended regular expressions in the script. -s, --separate consider files as separate rather than as a single continuous long stream. -u, --unbuffered load minimal amounts of data from the input files and flush the output buffers more often -z, --null-data separate lines by NUL characters --help display this help and exit --version output version information and exit If no -e, --expression, -f, or --file option is given, then the first non-option argument is taken as the sed script to interpret. All remaining arguments are names of input files; if no input files are specified, then the standard input is read. GNU sed home page: <http://www.gnu.org/software/sed/>. General help using GNU software: <http://www.gnu.org/gethelp/>. E-mail bug reports to: <bug-sed@gnu.org>. Be sure to include the word ``sed'' somewhere in the ``Subject:'' field. [root@node101.yinzhengjie.org.cn ~]#
3>.sed常用的编辑命令
"d": 删除模式空间匹配的行,并立即启用下一轮循环 "p": 打印当前模式空间内容,追加到默认输出之后 "a [\]text": 在指定行后面追加文本,支持使用\n实现多行追加 "i [\]text": 在行前面插入文本 "c [\]text": 替换行为单行或多行文本 "w /path/file": 保存模式匹配的行至指定文件 "r /path/file": 读取指定文件的文本至模式空间中匹配到的行后 "=": 为模式空间中的行打印行号 " !": 模式空间中匹配行取反处理 "s///": 查找替换,也支持使用其它分隔符,如:"s@@@","s###" "s///"替换标记如下所示: "g":
行内全局替换 "p":
显示替换成功的行 "w /PATH/FILE":
将替换成功的行保存至文件中
二.sed工具常用选项介绍
1>.使用编辑命令"d"(删除模式空间匹配的行,并立即启用下一轮循环)
[root@node101.yinzhengjie.org.cn ~]# seq 10 1 2 3 4 5 6 7 8 9 10 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# seq 10 | sed '3d' #删除第三行的默认输出 1 2 4 5 6 7 8 9 10 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#