Linux – “grep” from certain lines to the end of file

command linelinux

I have a text file similar to this:

line 1
line 2A
line 3
line 4A
line 5

I want to "grep" from "line 2A" to the end of file, something like this

cat file.txt|some_grep "line 2A"

Also, I want to "grep" from "line 2A" to the next line that contains "A", something like this

cat file.txt| some_grep "A"

I want this to print out:

line 2A
line 3
line 4A

Which command can help me achieve this?

Best Answer

(expanded from comment)

awk has a capability to select 'ranges' of lines which matches this need perfectly, as described in the the GNU-awk (gawk) manual. (This feature works in other awks but the gawk manual is easy to link.)

awk '/line 2A/,0' prints lines starting with the first one that matches line 2A and continuing until the end of input because 0 is a condition that is never true.

awk '/line 2A/,/A/&&!/line 2A/' starts printing with a line that matches line 2A and stops after a line that matches A but NOT line 2A (and thus cannot be the same line as the starting line). It will start again on a subsequent line 2A and so on; if you want to prevent that there are slightly more complicated ways to do so.

If the stopping lines always have some character other than 2 before the A this can be simplified to awk '/line 2A/,/[^2]A/' which stops after a line that matches any character other than 2, followed by A. You might want a variation of this, e.g. to stop on any-single-digit-A different from 2A, but not other As like WHAT; for that the stopping condition might be ,/line [013-9]A/.

Related Question