gpt4 book ai didi

regex - 如何使用 sed 命令从文件中删除包含特定字符串的行

转载 作者:太空狗 更新时间:2023-10-29 11:27:32 24 4
gpt4 key购买 nike

我有以下文件:

#!example
#!toto
example
#example
;example
toto
example

我想删除包含字符串 "example" 的行,但以 "#!" 开头的行除外。

所以结果文件应该是:

#!example
#!toto
toto

如何仅使用 sed 命令来实现?

最佳答案

这一行怎么样:

 sed '/^#!/n;/example/d' file

使用您的示例文本进行测试:

kent$  cat file
#!example
#!toto
example
#example
;example
toto
example

kent$ sed '/^#!/n;/example/d' file
#!example
#!toto
toto

如果你愿意,awk 也可以这样做:

kent$  awk '/^#!/ || !/example/' file                                                                                                                 
#!example
#!toto
toto

编辑

种子:

  • 如果行匹配 starting with #!,停止处理,转到下一行 (n)
  • 如果以上检查失败(不匹配#!),检查是否包含example,如果是,d删除(不在输出中打印)

  • 打印所有行:
    • #! 或 (||) 开头,不包含示例。

性能:

我真的说不准。因为要求很简单。您可以构建一个巨大的文件,然后使用时间 自行比较。

关于regex - 如何使用 sed 命令从文件中删除包含特定字符串的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16109207/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com