【问题标题】:use sed to search and replace patterns via regular expressions使用 sed 通过正则表达式搜索和替换模式
【发布时间】:2013-05-19 14:30:10
【问题描述】:

试图在文件中替换所有内容,包括密码直到空格。

密码=xx%40%25PKz3L2jTa HTTP

使用来自http://en.wikipedia.org/wiki/Regular_expression的正则表达式尝试了以下 sed 命令

sed 's/密码=(.)+/ /g' $file

sed 's/密码=[^ ]+/ /g' $file

以上都不起作用。为什么?

【问题讨论】:

  • 你必须转义+。试试这个: sed 's/password=[^ ]\+/ /g' $file
  • 可以使用sed -E开启扩展模式,支持+。

标签: regex sed


【解决方案1】:

尝试使用-r 参数:

sed -r 's/password=[^ ]+/ /g' $file

【讨论】:

  • 这依赖于 GNU sed-r 选项不是标准的)。使用经典(POSIX)sed,您可以编写一个简单的变体:sed 's/password=[^ ][^ ]*/ /g' $file
  • 谢谢。它总是对我有用,所以我忘记了它不是标准的。
【解决方案2】:

标准的sed 不理解“扩展”正则表达式,例如'+'。两种选择:

使用

启用扩展正则表达式
sed -E 's/password=[^ ]+/ /g' $file

或使用标准正则表达式

sed 's/password=[^ ]*/ /g' $file

我更喜欢第二个,因为它更便携,而且与第一个不同,它可以使用空密码字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 2019-09-04
    • 1970-01-01
    • 2010-11-19
    相关资源
    最近更新 更多