regex - 检查是否由 `perl -i -pe` 完成任何替换

标签 regex bash perl sed

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一样,但是如何获取修改后的内容 ("postgresql-9.4.service")存入文件,还是打印出来?

基本上我想要实现的是,在脚本执行后,它会告诉我它是否成功(以及实际替换的内容),如果不成功,我将显示一条消息,说明无法找到和替换的内容.


编辑:
突出显示我想获得(唯一的)修改后的内容,这表明我的脚本是成功的。因为使用 perl -i -pe 's/pattern/replace/' file,我不知道它返回的是真还是假。当然,我可以简单地执行 grep -E "/pettern/" 来找出答案,但这不是问题所在。

最佳答案

替换完成时,这段代码将抛出一个等于0的退出代码:

$ perl -i -pe '$M += s|(mariadb)(\.service)|postgresql-9.4\2|;END{exit 1 unless $M>0}' something.conf
$ echo $?
0

NO 替换完成时,返回 代码将为 1:

$ perl -i -pe '$M += s|(maria)(\.service)|postgresql-9.4\2|;END{exit 1 unless $M>0}' something.conf
$ echo $?
1

来自 Perl documentation

An END code block is executed as late as possible, that is, after perl has finished running the program and just before the interpreter is being exited, even if it is exiting as a result of a die() function. (But not if it's morphing into another program via exec, or being blown out of the water by a signal--you have to trap that yourself (if you can).) You may have multiple END blocks within a file--they will execute in reverse order of definition; that is: last in, first out (LIFO). END blocks are not executed when you run perl with the -c switch, or if compilation fails.

s operator 返回的替换

s/PATTERN/REPLACEMENT/msixpodualngcer

Searches a string for a pattern, and if found, replaces that pattern with the replacement text and returns the number of substitutions made.

关于regex - 检查是否由 `perl -i -pe` 完成任何替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34506284/

相关文章:

bash - 如何在 Bash 脚本中创建新的用户名和密码?

perl - Perl 的反引号、system 和 exec 有什么区别?

perl - 学习 Perl - 哪个版本?

Python:用字典中的实体替换某些 Unicode 实体

regex - 如何为由URL stub 中动态生成的数字组成的URL设置分析目标?

linux - awk 输出到变量

linux - 在文件中搜索文本字符串并替换它

javascript - JS : How to capitalize first letter of each symbol-separated word in a string?

javascript - 用于确保 HTTPS URL 架构的正则表达式

ruby - 如何删除 XML::Simple 输出中的 <opt> 标记?