grep -A< num>直到一个字符串 [英] grep -A <num> until a string

查看:122
本文介绍了grep -A< num>直到一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个包含以下内容的文件:

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

,我们希望grep这个文件,所以我们从第1章blah blah blah num
(下一章前一行)。



b $ b


  1. 说明字符串第1章等等等等

  2. 之后还有另一个以章节开始的行



  3. 一个虚拟的方法是

      grep -A< num> -i第1章< file> 

    足够大< num> so整个章节将在其中。

    解决方案

    使用 awk $ b

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

    如果标记 f 为真,它将打印行。

    第一章和下一章章节来更改标志。




    您可以使用范围 awk ,但是如果您有其他东西需要测试,它的灵活性会降低。

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


    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.

    解决方案

    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
    

    这篇关于grep -A&lt; num&gt;直到一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆