我有一个由几行文本组成的文件:
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
使用 awk(不显示匹配的行)
awk '/pattern/ {exit} {print}' file.txt
sed '/The second line/q0' file
或者,没有 gnu sed:
sed '/The second line/q' file
或者,使用 grep:
grep -B 9999999 "The second line"
sed "/$string/,\$d" inputfile
。
首先添加行号和删除行
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
不定期副业成功案例分享
co -p
),那么最好使用sed '/The second line/,$d'
表示法。;
工作后删除p
。