Find the answer to your Linux question:
Results 1 to 2 of 2
Hi, I have a file that I want to extract lines from if a pattern is found. However, I would also like to keep the first 5 lines even if ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Oct 2009
    Posts
    3

    Combine head and grep


    Hi,

    I have a file that I want to extract lines from if a pattern is found. However, I would also like to keep the first 5 lines even if that pattern does not appear in those lines.

    For example: here is a file:

    1
    2
    3
    4

    i a
    i a
    ii b
    ii b
    ii b
    iii c

    Now pretend I want the first 5 lines and lines containing 'b', then I want the following output:

    1
    2
    3
    4

    ii b
    ii b
    ii b

    Can anyone help?

    Thanks.

  2. #2
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,353
    awk=head+grep (plus a bunch of other sh!t)
    Code:
    awk '/b/ || NR<6' yourfile.txt

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •