简体   繁体   English

sed- 在模式前后插入文本

[英]sed- insert text before and after pattern

As a part of optimisation, I am trying to replace all Java files containing the string:作为优化的一部分,我正在尝试替换所有包含字符串的 Java 文件:

logger.trace("some trace message");

With:和:

if (logger.isTraceEnabled())
{
  logger.trace("some trace message");
}

NB Some trace message is not the exact string but an example.注意一些跟踪消息不是确切的字符串,而是一个示例。 This string will be different for every instance.这个字符串对于每个实例都是不同的。

I am using a bash script and sed but can't quite get the command right.我正在使用 bash 脚本和 sed 但不能完全正确地获得命令。

I have tried this in a bash script to insert before:我已经在 bash 脚本中尝试过这个插入之前:

traceStmt="if (logger.isTraceEnabled())
{
  "
find . -type f -name '*.java' | xargs sed "s?\(logger\.trace\)\(.*\)?\1${traceStmt}?g"

I have also tried different variants but with no success.我也尝试了不同的变体,但没有成功。

Try the following using GNU sed :使用 GNU sed尝试以下操作:

$ cat file1.java
1
2
logger.trace("some trace message");
4
5

$ find . -type f -name '*.java' | xargs sed 's?\(logger\.trace\)\(.*\)?if (logger.isTraceEnabled())\n{\n    \1\2\n}?'
1
2
if (logger.isTraceEnabled())
{
    logger.trace("some trace message");
}
4
5
$

If you would like to prevent adding new line endings如果您想阻止添加新的行尾

sed will add \n to the end of files that do not end in \n ) sed会将\n添加到不以\n结尾的文件的末尾)

You could try like:你可以试试:

perl -pi -e 's/logger.trace\("some trace message"\);/`cat input`/e' file.java

notice the ending /e注意结尾/e

The evaluation modifier s///e wraps an eval{...} around the replacement string and the evaluated result is substituted for the matched substring.评估修饰符s///eeval{...}包裹在替换字符串周围,评估结果将替换为匹配的 substring。 Some examples:一些例子:

In this case from your example, the file input contains:在本例中,文件input包含:

if (logger.isTraceEnabled())
{
  logger.trace("some trace message");
}

If have multiple files you could try:如果有多个文件,您可以尝试:

find . -type f -name '*.java' -exec perl -pi -e 's/logger.trace\("some trace message"\);/`cat input`/e' {} +

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM