![](/img/trans.png)
[英]How do I replace all lines after line XX in one file with content from another file?
[英]How do I delete all lines in a file starting from after a matching line?
我有一个由几行文本组成的文件:
The first line
The second line
The third line
The fourth line
我有一个字符串是其中之一: The second line
我想删除文件中的字符串及其后的所有行,因此它将删除字符串之外The third line
和The fourth line
。 该文件将变为:
The first line
我在google上搜索了一种解决方案,看来我应该使用sed
。 就像是:
sed 'linenum,$d' file
但是如何找到字符串的行号? 或者,我还应该怎么做?
如果您不想打印匹配的行(或以下任何行):
sed -n '/The second line/q;p' inputfile
这表示“当您到达与模式退出匹配的行时,否则打印每行”。 -n
选项可防止隐式打印,并且需要p
命令来显式打印行。
要么
sed '/The second line/,$d' inputfile
这表示“从输出中删除所有行,从匹配的行开始,一直到文件的末尾”。
但是第一个更快。 但是,它将完全退出处理,因此,如果您有多个文件作为参数,则第一个匹配文件之后的文件将不被处理。 在这种情况下,删除形式更好。
如果确实要打印匹配的行,但不打印以下任何行:
sed '/The second line/q' inputfile
这表示“打印所有行并在到达匹配的行时退出”(不使用-n
选项(不使用隐式打印))。
有关其他信息,请参见man sed 。
这比其他给定的解决方案要短一些。 使用大写字母Q退出可以避免打印当前行。
sed '/The second line/Q' file
要实际删除这些行,可以使用相同的语法。
sed -i '/The second line/Q' file
sed '/The second line/q0' file
或者,不使用gnu sed:
sed '/The second line/q' file
或者,使用grep:
grep -B 9999999 "The second line"
使用awk(不显示匹配的行)
awk '/pattern/ {exit} {print}' file.txt
首先添加行号并删除行
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
使用awk
awk 'NR!=3 && NR!=4' new.txt
The first line
The second line
awk '/The second line/{exit}1' file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.