grep -A <num> until a string

雨燕双飞 提交于 2019-12-11 08:06:55

问题


assuming that we have a file containing the following:

chapter 1 blah blah
blah num blah num
num blah num blah
...
blah num
chapter 2 blah blah

and we want to grep this file so we take the lines from chapter 1 blah blah to blah num (the line before the next chapter).

The only things we know are

  1. the stating string chapter 1 blah blah
  2. somewhere after that there is another line starting with chapter

a dummy way to do this is

grep -A <num> -i "chapter 1" <file>

with large enough <num> so the whole chapter will be in it.


回答1:


This is easy to do with awk

awk '/chapter/ {f=0} /chapter 1/ {f=1} f' file
chapter 1 blah blah
blah num blah num
num blah num blah
...
blah num

It will print the line if flag f is true.
The chapter 1 and next chapter to changes the flag.


You can use range with awk but its less flexible if you have other stuff to test.

awk '/chapter 1/,/chapter [^1]/ {if (!/chapter [^1]/) print}' file
chapter 1 blah blah
blah num blah num
num blah num blah
...
blah num



回答2:


sed -ne '/^chapter 1/,/^chapter/{/^chapter/d;p}' file



回答3:


You could do this through grep itself also but you need to enable Perl-regexp parameter P and z.

$ grep -oPz '^chapter 1[\s\S]*?(?=\nchapter)' file
chapter 1 blah blah
blah num blah num
num blah num blah
...
blah num

[\s\S]*? will do a non-greedy match of zero or more characters until the line which has the string chapter at the start is reached.

From man grep

-z, --null-data           a data line ends in 0 byte, not newline
-P, --perl-regexp         PATTERN is a Perl regular expression
-o, --only-matching       show only the part of a line matching PATTERN


来源:https://stackoverflow.com/questions/29180929/grep-a-num-until-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!