【发布时间】:2016-04-03 01:20:56
【问题描述】:
在GNU sed 中,我可以显示搜索模式替换成功的结果。简单的例子如下:
echo -e "nginx.service\nmariadb.service\nphp-fpm.service" > something.conf;
sed -ri 's|(mariadb)(\.service)|postgresql-9.4\2|w sed-output.log' something.conf;
[[ -s sed-output.log ]] && echo "Pattern found and modified. $(cat sed-output.log)" || echo "Pattern not found.";
因为sed在处理多行时有限制,所以我切换到perl。
echo -e "nginx.service\nmariadb.service\nphp-fpm.service" > something.conf;
perl -i -pe 's|(mariadb)(\.service)|postgresql-9.4\2|' something.conf;
上面的代码与sed 一样,但是我怎样才能将modified content ("postgresql-9.4.service") 放入文件中,或打印出来?
基本上我想要实现的是,在脚本执行后,它会告诉我它是否成功(以及实际替换的内容),如果没有,我将显示一条消息,说明找不到和替换的内容.
编辑:
突出显示我想获得(仅-)modified content,这表明我的脚本是成功的。因为使用perl -i -pe 's/pattern/replace/' file,我不知道它返回的是真还是假。当然,我可以简单地通过grep -E "/pettern/" 找出答案,但这不是问题。
【问题讨论】:
-
\2在替换表达式中应该是$2。-w会警告你这个错误。 -
顺便说一下,
s|mariadb(?=\.service)|postgresql-9.4|更快,虽然我怀疑它在这里会很重要。 -
当我使用
-pWe运行脚本测试时,确实建议使用 $1,只是想让两个脚本看起来相同。也是积极前瞻用法的一个很好的例子,我学到了一些东西,谢谢!