bash – 在文件中第一次出现特定字符串之前删除所有行

前端之家收集整理的这篇文章主要介绍了bash – 在文件中第一次出现特定字符串之前删除所有行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
基本上我有一个像这样的文件
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

猜你在找的Bash相关文章