基本上我有一个像这样的文件:
junk morejunk somestring bats car somestring bats car somestring bats car
我想在第一次出现somestring之前删除所有垃圾,以便文件看起来像
somestring bats car somestring bats car somestring bats car
我按照this question的建议使用sed -i’0,/ somestring /,d’file.txt,但是当我想将该行保留为第一行时,它会删除第一次出现somestring的行.
使用sed你可以使用:
sed -i '/somestring/,$!d' file
替换表达式的说明:
,
matches lines starting from where the first
address matches,and continues until the second match
(inclusively).
$
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
Delete the pattern space; immediately start next cycle.
结果:
$sed -i '/somestring/,$!d' file somestring bats car somestring bats car somestring bats car