Linux - "grep" from certain lines to the end of file

I want to "grep" from "line 2A" to the end of file:

sed -n '/2A/,$p'
  • -n : suppress sed default output
  • /2A/ : output lines from the first one containing "2A"
  • $ : to end of file

I want to "grep" from "line 2A" to the next line that contains "A":

sed -n '/2A/,/A/p'

I want to "grep" from the first line containing "A" to the next one:

printf "/A\n.+1,/A/p\nq" | ed -s

$ > foo echo "line 1
line 2A
line 3
line 4A
line 5"

$ sed -n '/2A/,$p' foo
line 2A
line 3
line 4A
line 5

$ sed -n '/2A/,/A/p' foo
line 2A
line 3
line 4A

$ printf "/A\n.+1,/A/p\nq" | ed -s foo
line 2A
line 3
line 4A

(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/.


I think the best way is to use grep in combination with cut and tail. First, use grep to get the line on which the desired string is (-n to output line number; -m 1 to stop searching after the first match):

grep -n -m 1 "somestring" filename.txt

This outputs the line number and the string itself. To cut away the string, we use cut (-f1: output first field; -d: use ":" as delimiter):

grep -n -m 1 "somestring" filename.txt | cut -f1 -d:

Next, we use the output of this command as parameter in tail. Normally, tail prints the last k lines, but using -n +k, we get tail to print from line k onwards. The total command is:

tail -n +`grep -n -m 1 "somestring" filename.txt | cut -f1 -d:` filename.txt

To output the lines until somestring use head instead of tail and -n -# instead of -n +#. You could also combine both to get the lines from one string until another.