如何删除从匹配行后开始的文件中的所有行?

我有一个由几行文本组成的文件:

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

我有一个字符串,它是其中一行: The second line

我想删除字符串和它后面的所有行在文件中,所以它将删除 The third lineThe fourth line除了字符串。文件会变成:

The first line

我在谷歌上搜索了一个解决方案,似乎我应该使用 sed。比如:

sed 'linenum,$d' file

但是如何找到字符串的行号呢? 或者,我应该怎么做呢?

112458 次浏览
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"

First add the line number and delete the 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

Using awk (not showing the matched line)

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

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.

awk '/The second line/{exit}1' file

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