如何从匹配行之后开始删除文件中的所有行? [英] How do I delete all lines in a file starting from after a matching line?

查看:22
本文介绍了如何从匹配行之后开始删除文件中的所有行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a file which is made up of several lines of text:

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

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

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

我想删除文件中的字符串和它后面的所有行,所以除了字符串之外还会删除第三行第四行.该文件将变为:

I want to delete the string and all lines after it in the file, so it will delete The third line and The fourth line in addition to the string. The file would become:

The first line

我在google上搜索了一个解决方案,看来我应该使用sed.类似的东西:

I've searched for a solution on google, and it seems that I should use sed. Something like:

sed 'linenum,$d' file

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

But how to find the line number of the string? Or, how else should I do it?

推荐答案

如果您不想打印匹配的行(或任何以下行):

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

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

这表示当您到达与模式匹配的行时退出,否则打印每一行".-n 选项可防止隐式打印,并且需要 p 命令来显式打印行.

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.

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

这表示打印所有行并在到达匹配行时退出"(未使用 -n 选项(无隐式打印)).

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

有关其他信息,请参阅 man sed.

See man sed for additional information.

这篇关于如何从匹配行之后开始删除文件中的所有行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆