Sed - 模式范围

Sed - 模式范围 首页 / Sed入门教程 / Sed - 模式范围

本章介绍了SED如何处理Pattern Range(模式范围) Pattern Range可以是简单的文本或复杂的正则表达式。下面的示例打印作者Paulo的所有书籍。

[jerry]$sed -n '/Paulo/p' books.txt

执行上述代码后,您将得到以下输出:

无涯教程网

3) The Alchemist, Paulo Coelho, 197 
5) The Pilgrimage, Paulo Coelho, 288

在上面的示例中,SED在每一行上操作,并且仅打印与字符串Paulo匹配的那些行。

无涯教程还可以将Pattern RangeAddress Range结合在一起。以下示例打印从"Alchemist"的第一个匹配开始到第五行。

[jerry]$sed -n '/Alchemist/, 5 p' books.txt

执行上述代码后,您将得到以下输出:

无涯教程网

3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
5) The Pilgrimage, Paulo Coelho, 288

找到第一个匹配项后,可以使用 Dollar($) 字符打印所有行。下面的示例查找 The 的第一个匹配项,并立即打印文件中的其余行

[jerry]$sed -n '/The/,$p' books.txt

执行上述代码后,您将得到以下输出:

无涯教程网

2) The Two Towers, J. R. R. Tolkien, 352 
3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432
5) The Pilgrimage, Paulo Coelho, 288 
6) A Game of Thrones, George R. R. Martin, 864 

还可以使用 逗号(,) 运算符指定多个Pattern Range(模式范围) 。下面的示例打印匹配 "Two" 和 "Pilgrimage" 之间存在的所有行。

[jerry]$sed -n '/Two/, /Pilgrimage/p' books.txt 

执行上述代码后,您将得到以下输出:

无涯教程网

2) The Two Towers, J. R. R. Tolkien, 352 
3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
5) The Pilgrimage, Paulo Coelho, 288

另外,无涯教程可以在模式范围内使用 plus(+) 运算符。下面的示例查找 "Two" 的第一个匹配项,并在其后打印接下来的4行。

[jerry]$sed -n '/Two/, +4 p' books.txt

执行上述代码后,您将得到以下输出:

无涯教程网

2) The Two Towers, J. R. R. Tolkien, 352 
3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
5) The Pilgrimage, Paulo Coelho, 288 
6) A Game of Thrones, George R. R. Martin, 864 

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

AI技术内参 -〔洪亮劼〕

Go语言核心36讲 -〔郝林〕

安全攻防技能30讲 -〔何为舟〕

微信小程序全栈开发实战 -〔李艺〕

TensorFlow 2项目进阶实战 -〔彭靖田〕

OAuth 2.0实战课 -〔王新栋〕

用户体验设计实战课 -〔相辉〕

超级访谈:对话汤峥嵘 -〔汤峥嵘〕

云计算的必修小课 -〔吕蕴偲〕

好记忆不如烂笔头。留下您的足迹吧 :)