作为Linux系统中文本处理的强力工具之一,sed功能强大,用法多变,值得我们好好学习。
sed是用于过滤和转换文本的流编辑器。
一般情况下sed把当前处理的行存储在临时缓冲区,按指定命令处理之后将缓冲区内容输出到屏幕,当然可以使用 -n 选项使得不打印内容到屏幕。另外这些操作默认对原文本没有影响,不会改变原来的文本内容。
但是如果我们确实想要将处理结果作用于原文本,使用 -i 选项将修改附加到原文件,注意要谨慎使用!
调用方式
- 命令行输入
sed -e 'command' input_file
- 脚本文件输入
sed -f script_file input_file下面通过一些实际操作说明一下 sed (未加说明即是指 sed (GNU sed) 4.2.2 ,下同)常用参数的含义和用法
首先获得实验文本
cv@cv: ~/myfiles$ touch test.txt cv@cv: ~/myfiles$ man sed | head -n 30 | tail -n 28 > test.txt cv@cv: ~/myfiles$ cat test.txttest.txt1 NAME 2 sed - stream editor for filtering and transforming text 3 4 SYNOPSIS 5 sed [OPTION]... {script-only-if-no-other-script} [input-file]... 6 7 DESCRIPTION 8 Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an 9 editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed's ability to filter text 10 in a pipeline which particularly distinguishes it from other types of editors. 11 12 -n, --quiet, --silent 13 14 suppress automatic printing of pattern space 15 16 -e script, --expression=script 17 18 add the script to the commands to be executed 19 20 -f script-file, --file=script-file 21 22 add the contents of script-file to the commands to be executed 23 24 --follow-symlinks 25 26 follow symlinks when processing in place 27 28 -i[SUFFIX], --in-place[=SUFFIX]