som-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:03:09 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com