【问题标题】:How to Inserting string after matching pattern如何在匹配模式后插入字符串
【发布时间】:2013-06-07 15:44:32
【问题描述】:

在包含数千个 PHP 文件的项目中,我需要在每个 catch 之后插入一条调试指令。

我要匹配模式

catch (

所以在每个匹配的模式之后,我想插入指令:

Reporter::send_exception($e);

我一直在尝试使用 sed 来完成此操作,但我一直未能成功。

这是我正在使用的 sed 命令:

sed -e '/catch \(/{:a,n:\ba;i\Reporter::send_exception\(\$e\);\g' -e '}' RandomFile.php

任何帮助撰写本文将不胜感激!

我在 Stack Overflow 中看到了针对同一问题的其他解决方案,但这些解决方案都没有奏效。

谢谢

编辑

基本上我的文件看起来很像这样:

try {
  do_something();
} catch ( AnyKindOfException $e) {
  Reporter::send_exception($e); // Here's where I want to insert the line
  // throws generic error page
}

这就是我想匹配catch \(*$的原因 然后插入 Reporter::send_exception($e)

【问题讨论】:

  • 不要逃避括号
  • 您是在匹配模式之后的同一行插入,还是要在下一行插入?
  • 我想在下一行插入,我将编辑我的问题以提供更多上下文
  • sed's i 命令在匹配模式的行之前插入文本,所以这绝对不是你想要的。

标签: regex perl shell sed


【解决方案1】:

我想您想在包含catch ( 的行之后插入文本。

perl -p 下,$_ 包含读取的行,代码执行后$_ 包含的任何内容都将被打印。因此,我们只需在适当的时候将要插入的行附加到$_

perl -pe'$_.="  Reporter::send_exception(\$e);\n" if /catch \(/'

perl -pe's/catch\(.*\n\K/  Reporter::send_exception(\$e);\n/'

用法:

perl -pe'...' file.in >file.out    # From file to STDOUT
perl -pe'...' <file.in >file.out   # From STDIN to STDOUT
perl -i~ -pe'...' file             # In-place, with backup
perl -i -pe'...' file              # In-place, without backup

【讨论】:

  • 我想知道为什么你没有在前面连接换行符,然后我记得 Perl 保留了每一行的换行符。
【解决方案2】:

您可以使用sed \a 命令来执行此操作,该命令允许您附加该行。语法是:

sed '/PATTERN/ a\
    Line which you want to append' filename

所以你的情况是:

sed '/catch (/ a\
Reporter::send_exception($e);' filename

测试:

$ cat fff
adfadf
afdafd
catch (
dfsdf
sadswd

$ sed '/catch (/ a\
Reporter::send_exception($e);' fff
adfadf
afdafd
catch (
Reporter::send_exception($e);
dfsdf
sadswd

【讨论】:

    【解决方案3】:

    我相信这应该可以解决问题:

    sed -e 's/catch\s*(/catch (\n\tReporter::send_exception($e);/'
    

    【讨论】:

      【解决方案4】:

      尝试:

      sed 's/catch (/\0Reporter::send_exception($e);/g'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多