首先准备一段文本:test01.txt
begin
how are you?
fine thank you,and you?
i am fine too.
end
^Bbegin
please give me the paper.
ok,here you are.
thank you
^Cend
注意这里的^B和^C属于ascii码形式,^B在16进制下是x02,^C在16进制下是x03.
题目一:截取以begin开头和end结尾的段落即:
begin
how are you?
fine thank you,and you?
i am fine too.
end
答案:sed -n '/^begin/,/^end/p' test01.txt
解释:-n 是Suppresses the default output,格式是sed -n ‘/开始行/,/结束行/p’ test01.txt,这里开始行定义为^begin表示以begin字符开始的行,结束行^end表示以end开始的行。然后截取中间部分。
题目二:截取以^Bbegin开始和^Cend结尾的段落即:
^Bbegin
please give me the paper.
ok,here you are.
thank you
^Cend
答案:sed -n '/^^Bbegin/,/^^Cend/p' test01.txt
解释:这里和上面答案的有点区别就是^B和^C,其实他们俩不是简单的'^B'和'^C'字符组合,显示有点迷惑,而真实是16位形式x02和x03。所以敲门就是在命令行里怎么输入16进制形式。要想打出^B可以这么输入:在命令行,先按ctl+v,然后再按ctl+B。这样x02就输入了,而显示为^B不要糊涂了。同理x03也是先按ctl+v再按ctl+C。这里要注意。
另注:
-e是进行多行编辑,即对输入行应用多条sed命令时使用。
-n 取消默认的输出
p 打印行
上面两个语句都是截取文本并打印到屏幕,如果要截取并存到一个文件里,请使用重定向'>'(先清空文件再输出)和'>>'(追加输出);
如:sed -n '/^begin/,/^end/p' test01.txt > test01.txt.sed 追加形式是 sed -n '/^begin/,/^end/p' test01.txt >> test01.txt.sed