加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 01:16:32 所属栏目:安全 来源:网络整理
导读:基本上我有一个像这样的文件: junkmorejunksomestringbatscarsomestringbatscarsomestringbatscar 我想在第一次出现somestring之前删除所有垃圾,以便文件看起来像 somestringbatscarsomestringbatscarsomestringbatscar 我按照this question的建议使用sed -
基本上我有一个像这样的文件:
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读