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 otherawk
s but thegawk
manual is easy to link.)awk '/line 2A/,0'
prints lines starting with the first one that matchesline 2A
and continuing until the end of input because0
is a condition that is never true.awk '/line 2A/,/A/&&!/line 2A/'
starts printing with a line that matchesline 2A
and stops after a line that matchesA
but NOTline 2A
(and thus cannot be the same line as the starting line). It will start again on a subsequentline 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 theA
this can be simplified toawk '/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 likeWHAT
; for that the stopping condition might be,/line [013-9]A/
.