How to delete all lines in a file, starting from the corresponding line?

I have a file consisting of several lines of text:

The first line The second line The third line The fourth line 

I have a line that is one of the lines: The second line

I want to delete the line and all the lines after it in the file, so it will delete The third line and The fourth line in addition to the line. The file will look like this:

 The first line 

I was looking for a solution for google and it seems to me that I should use sed . Something like:

 sed 'linenum,$d' file 

But how to find the line number of a line? Or, how else should I do this?

+49
linux bash sed
Mar 08 '11 at 1:23
source share
6 answers

If you do not want to print a consistent line (or any of the following lines):

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

This suggests that "when you reach the line that matches the pattern, close, otherwise print each line." The -n prevents implicit printing, and p requires explicitly printing lines.

or

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

This says: "Remove all lines from the output starting with the matching line and continue to the end of the file."

but the first is faster.

If you want to print a consistent line, but not the following lines:

 sed '/The second line/q' inputfile 

This means that "print all lines and exit when the matching line is reached" (the -n option (without implicit printing) is not used).

See man sed for more information.

+81
Mar 08 2018-11-11T00:
source share

This is slightly shorter than the other data solutions. Quitting the use of capital Q avoids printing the current line.

  sed '/The second line/Q' file 

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

  sed -i '/The second line/Q' file 
+15
Jun 11 '14 at 10:47
source share
 sed '/The second line/q0' file 

Or without gnu sed:

 sed '/The second line/q' file 

Or using grep:

 grep -B 9999999 "The second line" 
+5
Mar 08 '11 at 1:26
source share

Using awk (doesn't display a consistent string)

 awk '/pattern/ {exit} {print}' file.txt 
+4
Mar 08 '11 at 1:45
source share

First add line number and delete line

 cat new.txt The first line The second line The third line The fourth line cat new.txt | nl 1 The first line 2 The second line 3 The third line 4 The fourth line cat new.txt | nl | sed "/2/d" 1 The first line 3 The third line 4 The fourth line cat new.txt | nl |sed "3d;4d" 1 The first line 2 The second line 

using awk

 awk 'NR!=3 && NR!=4' new.txt The first line The second line 
0
Mar 08 2018-11-11T00:
source share
 awk '/The second line/{exit}1' file 
0
Mar 08 '11 at 1:50
source share



All Articles