。[sam@Linux_chenwy sam]$ cat quote.txt
The honeysuckle band played all night long for only $90.
It was an evening of splendid music and company.
Too bad the disco floor fell through at 23:00.
The local nurse Miss P.Neave was in attendance.
1 使用p(rint)显示行
只打印第二行,用-n
[sam@Linux_chenwy sam]$ sed -n '2p' quote.txt
It was an evening of splendid music and company.
2 打印范围
可以指定行的范围,现打印1到3行,用逗号分隔行号。
[sam@Linux_chenwy sam]$ sed -n '1,3p' quote.txt
The honeysuckle band played all night long for only $90.
It was an evening of splendid music and company.
Too bad the disco floor fell through at 23:00.
3 打印模式
假定要匹配单词N e a v e,并打印此行,方法如下。使用模式/ p a t t e r n /格式,这里为/ N e a v e /。
[sam@Linux_chenwy sam]$ sed -n '/The/p' quote.txt
The honeysuckle band played all night long for only $90.
The local nurse Miss P.Neave was in attendance.
4 使用模式和行号进行查询
可以将行号和模式结合使用。假定要改动文件q u o t e . t x t最后一行中的单词t h e,使用s e d查询t h e,返回两行:
[sam@Linux_chenwy sam]$ sed -n '/The/p' quote.txt
The honeysuckle band played all night long for only $90.
The local nurse Miss P.Neave was in attendance.
使用模式与行号的混合方式可以剔除第一行,格式为l i n e _ n u m b e r, / p a t t e r n /。逗号用来分隔行号与模式开始部分。为达到预期结果,使用4 , / t h e /。意即只在第四行查询模式t h e,命令如下:
[sam@Linux_chenwy sam]$ sed -n '4,/The/p' quote.txt
The local nurse Miss P.Neave was in attendance.
上面有错,其实是把第四行后的都打出来了
这个模式应该哪果指定行找不到符合条件的,就从下一行开始查找,直到找到为止,并把,找到行之前的全部打打印出来。
如果指定行本身就符合条伯,把本行及后面的行的全部打印出来
5 匹配元字符
匹配元字符$前,必须使用反斜线\屏蔽其特殊含义。模式为/\$/ p。
[sam@Linux_chenwy sam]$ sed -n '/\$/p' quote.txt
The honeysuckle band played all night long for only $90.
6 显示整个文件
要打印整个文件,只需将行范围设为第一行到最后一行1 , $。$意为最后一行。
[sam@Linux_chenwy sam]$ sed -n '1,$p' quote.txt
The honeysuckle band played all night long for only $90.
It was an evening of splendid music and company.
Too bad the disco floor fell through at 23:00.
The local nurse Miss P.Neave was in attendance.
7 任意字符
匹配任意字母,后跟任意字母的0次或多次重复,并以i n g结尾,模式为/ . * i n g /。可以使用这个模式查询以i n g结尾的任意单词。
[sam@Linux_chenwy sam]$ sed -n '/.*ing/p' quote.txt
It was an evening of splendid music and company.
8 首行
要打印文件第一行,使用行号:
[sam@Linux_chenwy sam]$ sed -n '1p' quote.txt
The honeysuckle band played all night long for only $90.
9 最后一行
要打印最后一行,使用$。$是代表最后一行的元字符。
[sam@Linux_chenwy sam]$ sed -n '$p' quote.txt
The local nurse Miss P.Neave was in attendance.
10 打印行号
要打印行号,使用等号=。打印模式匹配的行号,使用格式/ p a t t e r n / =。
[sam@Linux_chenwy sam]$ sed -e '/music/=' quote.txt
The honeysuckle band played all night long for only $90.
2
It was an evening of splendid music and company.
Too bad the disco floor fell through at 23:00.
The local nurse Miss P.Neave was in attendance.
整个文件都打印出来,并且匹配行打印了行号。如果只关心实际行号,使用- e选项。
[sam@Linux_chenwy sam]$ sed -n '/music/=' quote.txt
2
如果只打印行号及匹配行,必须使用两个s e d命令,并使用e选项。第一个命令打印模式匹配行,第二个使用=选项打印行号,格式为sed -n -e /pattern/p -e /pattern/=
[sam@Linux_chenwy sam]$ sed -n -e '/music/p' -e '/music/=' quote.txt
It was an evening of splendid music and company.
2
阅读(1380) | 评论(0) | 转发(0) |