Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux sed-在模式前后插入文本_Linux_Bash_Sed - Fatal编程技术网

Linux sed-在模式前后插入文本

Linux sed-在模式前后插入文本,linux,bash,sed,Linux,Bash,Sed,作为优化的一部分,我尝试替换包含以下字符串的所有Java文件: logger.trace("some trace message"); 与: 注意:某些跟踪消息不是确切的字符串,而是一个示例。此字符串对于每个实例都是不同的 我正在使用bash脚本和sed,但不能完全正确地获得命令 我曾在bash脚本中尝试过插入以下内容: traceStmt="if (logger.isTraceEnabled()) { " find . -type f -name

作为优化的一部分,我尝试替换包含以下字符串的所有Java文件:

logger.trace("some trace message");
与:

注意:某些跟踪消息不是确切的字符串,而是一个示例。此字符串对于每个实例都是不同的

我正在使用bash脚本和sed,但不能完全正确地获得命令

我曾在bash脚本中尝试过插入以下内容:

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

我也尝试过不同的变体,但没有成功。

使用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
$

如果要防止添加新行结尾

sed
将在不以
\n
结尾的文件末尾添加
\n

你可以试试:

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

求值修饰符
s///e
围绕替换字符串包装一个
eval{…}
,并用求值结果替换匹配的子字符串。一些例子:

在本例中,您的示例中的文件
input
包含:

if (logger.isTraceEnabled())
{
  logger.trace("some trace message");
}
如果您有多个文件,可以尝试:

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

控制台输出显示更改,但文件没有更改。@karen。使用
sed
-i
选项进行现场更换,即“查找”-键入f-name'*.java'| xargs sed-i?(logger\.trace)(*)如果(logger.isTraceEnabled())\n{\n\1\2\n}?“
find . -type f -name '*.java' -exec perl -pi -e 's/logger.trace\("some trace message"\);/`cat input`/e' {} +