如何在匹配模式后插入字符串

时间:2013-06-11 17:22:27

标签: regex perl shell sed

我需要在包含数千个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)

4 个答案:

答案 0 :(得分:5)

您可以使用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

答案 1 :(得分:2)

我认为你想在包含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

答案 2 :(得分:1)

尝试:

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

答案 3 :(得分:0)

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

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