我有一个由几行文本组成的文件:
The first line
The second line
The third line
The fourth line
Run Code Online (Sandbox Code Playgroud)
我有一个字符串是其中一行: The second line
我要删除字符串,并在文件中后,所有行,因此它会删除The third line,并The fourth line在除了字符串.该文件将成为:
The first line
Run Code Online (Sandbox Code Playgroud)
我在谷歌搜索了一个解决方案,似乎我应该使用sed.就像是:
sed 'linenum,$d' file
Run Code Online (Sandbox Code Playgroud)
但是如何找到字符串的行号?或者,我该怎么做呢?
Pau*_*ce. 112
如果您不想打印匹配的行(或任何后续行):
sed -n '/The second line/q;p' inputfile
Run Code Online (Sandbox Code Playgroud)
这表示"当您到达与模式退出匹配的行时,否则打印每一行".该-n选项可防止隐式打印,并且p需要命令才能显式打印行.
要么
sed '/The second line/,$d' inputfile
Run Code Online (Sandbox Code Playgroud)
这表示"从匹配行开始并继续到文件末尾的输出中删除所有行".
但第一个更快.但是它将完全退出处理,因此如果您有多个文件作为参数,则不会处理第一个匹配文件之后的文件.在这种情况下,删除表单更好.
如果您确实要打印匹配的行,而不是以下任何行:
sed '/The second line/q' inputfile
Run Code Online (Sandbox Code Playgroud)
这表示"打印所有行并在达到匹配的行时退出"(-n不使用选项(无隐式打印)).
有关其他信息,请参阅man sed.
jaa*_*aap 22
这比其他给定的解决方案略短.使用大写Q退出可避免打印当前行.
sed '/The second line/Q' file
Run Code Online (Sandbox Code Playgroud)
要实际删除行,您可以使用相同的语法.
sed -i '/The second line/Q' file
Run Code Online (Sandbox Code Playgroud)
sed '/The second line/q0' file
Run Code Online (Sandbox Code Playgroud)
或者,没有gnu sed:
sed '/The second line/q' file
Run Code Online (Sandbox Code Playgroud)
或者,使用grep:
grep -B 9999999 "The second line"
Run Code Online (Sandbox Code Playgroud)