bash Sed/Awk - 在模式 x 和 y 之间拉线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15769411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:04:37  来源:igfitidea点击:

Sed/Awk - pull lines between pattern x and y

bashsedawk

提问by Numpty

I've got some large CSV files where I'd like to extract all data between Line X that includes pattern 'x' and Line Y that includes pattern 'y'

我有一些大型 CSV 文件,我想在其中提取包含模式“x”的 X 行和包含模式“y”的 Y 行之间的所有数据

For example:

例如:

other_data
Header
data
data
data
Footer
other_data

I want to be able to pipe everything between (and including) Header -> Footer to a new file.

我希望能够将(包括)Header -> Footer 之间的所有内容通过管道传输到新文件。

Thanks!

谢谢!

回答by FatalError

Using awkit's pretty straightforward:

使用awk它非常简单:

awk '/Header/ { show=1 } show; /Footer/ { show=0 }'

Basically keep state in a variable named show. When we hit the Header we turn it on, Footer we turn it off. While it's on, the showrule executes the default action of printing the record.

基本上将状态保存在名为show. 当我们点击页眉时,我们将其打开,页脚我们将其关闭。当它打开时,show规则执行打印记录的默认操作。

回答by Beta

It's pretty straightforward in sed:

在 sed 中非常简单:

sed -n '/Header/,/Footer/p'

or

或者

sed '/Header/,/Footer/!d'

回答by Chris Seymour

Another way with awk:

另一种方式awk

awk '/Header/,/Footer/' file
Header
data
data
data
Footer

Just redirect the output to save in a newfile:

只需重定向输出以保存在新文件中:

awk '/Header/,/Footer/' file > newfile

回答by potong

This might work for you (GNU sed):

这可能对你有用(GNU sed):

 sed '/^Header/,/^Footer/w new_file' file