Sed是一个流编辑器 stream editor,这也是sed这个名字的由来。
替换
先来个简单的替换的例子,把某个单词替换为另一个单词,以下是我的第一次sed实践:
hope@hope:~/sed$ cat demo.txt
The Cholesky algorithm was not published until after Cholesky’s death, but it was later examined by Turing and Wilkinson4 and others.
hope@hope:~/sed$ sed 's/after/aftter/' demo.txt
The Cholesky algorithm was not published until aftter Cholesky’s death, but it was later examined by Turing and Wilkinson4 and others.
提取某行
使用-n选项限制输出,比如说只显示第五行,可以sed -n ‘5p’,以下是我的实践:
hope@hope:~/sed$ vi pippa.txt
hope@hope:~/sed$ cat pippa.txt
Pippa
The year’s at the spring,
The day’s at the morn;
Morning’s at seven;
The hillside’s dew pearled;
The lark’s on the wing;
The snail’s on the thorn;
God’s in His heaven—
All’s right with the world!
ROBERT BROWNING.
hope@hope:~/sed$ sed -n '5p' pippa.txt
The hillside’s dew pearled;
hope@hope:~/sed$
多文件处理
如果是多个文件,将会拼接为一个文件,我举个例子:
hope@hope:~/sed$ cat farewell.txt
A Farewell
My fairest child, I have no song to give you;
No lark could pipe to skies so dull and gray;
Yet, ere we part, one lesson I can leave you
For every day.
Be good, sweet maid, and let who will be clever;
Do noble things, not dream them all day long:
And so make life, death, and that vast forever
One grand, sweet song.
CHARLES KINGSLEY.
hope@hope:~/sed$ sed -n '11p' pippa.txt farewell.txt
A Farewell
hope@hope:~/sed$
拼接为一个长文件后,第11行才是第二个文件的第一行。
提取多行
提取多行文本无非是用分号隔开,语法上比较简单。如下面的例子:
hope@hope:~/sed$ sed -n '1p;5p;6p;9p' pippa.txt
Pippa
The hillside’s dew pearled;
The lark’s on the wing;
All’s right with the world!
hope@hope:~/sed$
提取尾行
提取最后一行,用$p就可以了,如下:
hope@hope:~/sed$ sed -n '$p' pippa.txt
ROBERT BROWNING.
hope@hope:~/sed$
间隔行
为了方便,我把用于实验的文本每行前面都加上行号,文本内容如下:
1 Pippa
2 The year’s at the spring,
3 The day’s at the morn;
4 Morning’s at seven;
5 The hillside’s dew pearled;
6 The lark’s on the wing;
7 The snail’s on the thorn;
8 God’s in His heaven—
9 All’s right with the world!
10 ROBERT BROWNING.
间隔行的语法是m~n,m是开始行,n是间隔多少行,用例子说话:
hope@hope:~/sed$ sed -n '1~2p' pippa.txt
1 Pippa
3 The day’s at the morn;
5 The hillside’s dew pearled;
7 The snail’s on the thorn;
9 All’s right with the world!
hope@hope:~/sed$ sed -n '1~3p' pippa.txt
1 Pippa
4 Morning’s at seven;
7 The snail’s on the thorn;
10 ROBERT BROWNING.
hope@hope:~/sed$
行范围
范围使用逗号,用起来比较简单,如下:
hope@hope:~/sed$ sed -n '1,3p' pippa.txt
1 Pippa
2 The year’s at the spring,
3 The day’s at the morn;
脚本
如果命令比较长,可以写入脚本中,然后使用f参数调用。我举个例子:
hope@hope:~/sed$ vi 1to3p.sed
hope@hope:~/sed$ cat 1to3p.sed
1,3p
hope@hope:~/sed$ sed -n -f 1to3p.sed pippa.txt
1 Pippa
2 The year’s at the spring,
3 The day’s at the morn;
hope@hope:~/sed$