2

I have found I can use grep -A10 "search string" file.txt to show 10 lines after the search string is found in the file or grep -B10 "search string" file.txt to show the 10 lines before. How can I set it to show all of the lines before or after the match?

For example, I have this file:

This is some text.
This is some more text.
This is some text.
This is some more text.
This is some text.
This is some yet more text.
This is some text.
---
This is some more text.
This is some text.
This is some more text.

I need, in the first search, to print all the stuff found before "---", regardless of how many lines there are.

And I need in the second search, to print all the stuff found after "---", regardless of how many lines there are after that.

oguz ismail
  • 1
  • 16
  • 47
  • 69
Village
  • 22,513
  • 46
  • 122
  • 163
  • 1
    grep can't do that. – oguz ismail Dec 25 '20 at 05:14
  • This might help with GNU grep: `grep -zo -- '.*---' file` and `grep -zo -- '---.*' file` – Cyrus Dec 25 '20 at 08:03
  • For the sake of completeness: `grep -C10 "search string" file.txt`? gives both the 10 lines before and after. If you know the size of the file, you can obviously type `grep -C99 "search string" file.txt` where 99 > that size (in terms of lines). – Cadoiz Nov 07 '22 at 14:58

2 Answers2

7

This could be easily done in awk, in case you are ok with it.

1st solution: To get all lines till first string is found one could try:

awk '1; /test/{exit}' Input_file

2nd solution: To get line from a string is match to till end try:

awk '/test/{found=1} found' Input_file
oguz ismail
  • 1
  • 16
  • 47
  • 69
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • No, I mean, I don't want to limit it to 10, I mean if there are 1000 lines before, or any number up to infinity. – Village Dec 25 '20 at 05:11
  • @Village, sorry, could you please elaborate more on this one to me, I didn't get it fully, I thought you want 10 lines before and after match, is it you want to take number of lines from a variable etc? – RavinderSingh13 Dec 25 '20 at 05:12
  • I am, I need to show all of the lines before. Or, in a different search, find all of the lines after. – Village Dec 25 '20 at 05:14
  • @Village, ok sure, could you please do add some samples in your question for better understanding of your question please. – RavinderSingh13 Dec 25 '20 at 05:15
  • 1
    @Village, could you please try my edited solutions and let me know if that helps you. – RavinderSingh13 Dec 25 '20 at 05:20
0

It seems that your need is equivalent to find the line number of line with the matched pattern. If the line number is available, you could use head or tail command.

To get the line number, you could first add line number to each line by cat -n and then do the grep

ryan2718281
  • 139
  • 5