在命令行定义编辑器命令
默认情况下,sed编辑器会将指定的命令应用到STDIN输入流上。这样可以直接将数据通过管道输入sed编辑器处理:
$ echo "This is a test" | sed 's/test/big test/'
This is a big test
$
这个例子在sed编辑器中使用了s命令。s命令会用斜线间指定的第二个文本字符串来替换第一个文本字符串模式。在本例中是big test替换了test。
在运行这个例子时,结果应该立即就会显示出来。这就是使用sed编辑器的强大之处。可以同时对数据做出多处修改,而所消耗的时间却只够一些交互式编辑器启动而已。
当然,这个简单的测试只是修改了一行数据。不过就算编辑整个文件,处理速度也相差无几。
$ cat data.txt
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
$
$ sed 's/dog/cat/' data.txt
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy cat.
$
sed命令几乎瞬间就执行完并返回数据。在处理每行数据的同时,结果也显示出来了。可以在sed编辑器处理完整个文件之前就开始观察结果。
重要的是,要记住,sed编辑器并不会修改文本文件的数据。它只会将修改后的数据发送到STDOUT。如果查看原来的文本文件,它仍然保留着原始数据。
$ cat data.txt
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
$