在文件中第一次出现特定字符串之前删除所有行 [英] Delete all lines before first occurrence of specific string in file
问题描述
基本上我有一个类似的文件:
Basically I have a file like:
junk
morejunk
somestring
bats
car
somestring
bats
car
somestring
bats
car
我想在第一次出现 somestring
之前删除所有的 junk
所以文件看起来像
and I want to remove all of the junk
before the first occurrence of somestring
so the file looks like
somestring
bats
car
somestring
bats
car
somestring
bats
car
我遵循了 this question 使用 sed -i '0,/somestring/,d' file.txt
但它删除了第一次出现 somestring 的行
,当我想将该行保留为第一行时.
I followed the advice from this question to use sed -i '0,/somestring/,d' file.txt
but it deletes the line with the first occurrence of somestring
, when I want to keep that line as the first line.
推荐答案
使用 sed
你可以使用:
sed -i '/somestring/,$!d' file
替换表达式的解释:
,
匹配从第一行开始的行地址匹配,并一直持续到第二个匹配(包括在内).
,
matches lines starting from where the first address matches, and continues until the second match (inclusively).
$
匹配输入的最后一个文件的最后一行,或 -i 或 -s 选项时每个文件的最后一行指定.
$
matches the last line of the last file of input,
or the last line of each file when the -i or -s options are
specified.
!
如果字符跟随地址范围,则只有行与地址范围不匹配的将被选中.
!
If the character follows an address range, then only lines
which do not match the address range will be selected.
d
删除模式空间;立即开始下一个循环.
d
Delete the pattern space; immediately start next cycle.
结果:
$ sed -i '/somestring/,$!d' file
somestring
bats
car
somestring
bats
car
somestring
bats
car
这篇关于在文件中第一次出现特定字符串之前删除所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!