How do I delete all lines in a file starting from after a matching line?

Solution 1:

If you don't want to print the matched line (or any following lines):

sed -n '/The second line/q;p' inputfile

This says "when you reach the line that matches the pattern quit, otherwise print each line". The -n option prevents implicit printing and the p command is required to explicitly print lines.

or

sed '/The second line/,$d' inputfile

This says "delete all lines from the output starting at the matched line and continuing to the end of the file".

but the first one is faster. However it will quit processing completely so if you have multiple files as arguments, the ones after the first matching file won't be processed. In this case, the delete form is better.

If you do want to print the matched line, but not any following lines:

sed '/The second line/q' inputfile

This says "print all lines and quit when the matched line is reached" (the -n option (no implicit print) is not used).

See man sed for additional information.

Solution 2:

This is a bit shorter than other given solutions. Quit using capital Q avoids printing the current line.

 sed '/The second line/Q' file

To actually delete the lines you can use the same syntax.

 sed -i '/The second line/Q' file

Solution 3:

Using awk (not showing the matched line)

awk '/pattern/ {exit} {print}' file.txt