【问题标题】:Sed replace with regexsed 替换为正则表达式
【发布时间】:2014-10-04 09:41:02
【问题描述】:

我无法使用 sed 进行简单的正则表达式替换。这是我遇到的例子。

我正在尝试替换文件中的行,来自:

select * from mytable where mytable.s_id=274
select * from mytable where mytable.s_id=275
select * from mytable where mytable.s_id=276
select * from othertable where othertable.id=?
select * from table3 where table3.name=?

到这里:

select * from mytable where mytable.s_id=?
select * from mytable where mytable.s_id=?
select * from mytable where mytable.s_id=?
select * from othertable where othertable.id=?
select * from table3 where table3.name=?

我现在正在使用 sed:

cat log | sed 's/where mytable\.s_id=[0-9]+/where mytable.s_id=/g' | sort

但是我在 sed ('s/where mytable\.s_id=[0-9]+/where mytable.s_id=/g') 中使用的正则表达式并不能替代任何东西。

我正在阅读尽可能多的文档,但我阅读的所有内容都不同,做事方式也不同,所以我有点迷茫。使用 sed 进行正则表达式替换的规范方法是什么,在我的特殊情况下会是什么样子?

注意:我简化了我面临的问题。我确实想使用 sed(最终学会使用它)并且我 确实想通过管道传输输入和输出(而不是就地编辑文件),因为命令行我用的其实比那个复杂。

【问题讨论】:

  • .s和id之间有空格还是下划线?
  • 您似乎在使用支持+ 的GNU sed。您要么需要通过添加 \ 来转义它,要么使用扩展正则表达式开关 -r 运行 sed

标签: regex file-io sed


【解决方案1】:
cat log | sed 's/where mytable\.s_id=[0-9]\+/where mytable.s_id=?/g'

在 + 之前只是一个反斜杠。

【讨论】:

  • 谢谢!为什么需要转义?我觉得必须转义一个特殊字符很奇怪,而我不需要转义[0-9]。例如,我是否还需要转义*
  • 是的,您需要将一些特殊字符转义为 . + 和 * 实际上这些字符被解释为正则表达式的规范。如果您想了解更多信息,请尝试在网络上获取教程。
【解决方案2】:

引用+

sed 's/where mytable\.s_id=[0-9]\+/where mytable.s_id=?/g'

【讨论】:

    【解决方案3】:

    AFAIK,有些 sed 不知道 +。因此,试试这个:

     cat log | sed 's/where mytable\.s_id=[0-9]*/where mytable.s_id=?/g' | sort
    

    编辑:+ 是一个 GNU 扩展,如果您使用它(并且您的 sed 知道它),您必须像 choroba 建议的那样转义它。

    【讨论】:

      【解决方案4】:

      如果你对 awk 感兴趣

      awk -F= '{$2="=?";print}' temp
      

      以下测试;

      > cat temp
      select * from mytable where mytable.s_id=275
      select * from mytable where mytable.s_id=276
      select * from othertable where othertable.id=?
      select * from table3 where table3.name=?
      > awk -F= '{$2="=?";print}' temp
      select * from mytable where mytable.s_id =?
      select * from mytable where mytable.s_id =?
      select * from othertable where othertable.id =?
      select * from table3 where table3.name =?
      

      【讨论】:

      • 我想使用 sed,我在问题中强调了这一点
      猜你喜欢
      • 2012-01-26
      • 2018-08-22
      • 2021-12-31
      • 2013-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      相关资源
      最近更新 更多