简体   繁体   中英

sed- insert text before and after pattern

As a part of optimisation, I am trying to replace all Java files containing the string:

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.

I have tried this in a bash script to insert before:

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 :

$ 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 )

You could try like:

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

notice the ending /e

The evaluation modifier s///e wraps an eval{...} around the replacement string and the evaluated result is substituted for the matched substring. Some examples:

In this case from your example, the file input contains:

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' {} +

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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