Check if there was any replacement made by `perl -i -pe`

In GNU sedI can display the result of the successful substitution of the search pattern. A simple example:

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.";

Since it sedhas a limitation when working with multi-lines, I switched to perl.

echo -e "nginx.service\nmariadb.service\nphp-fpm.service" > something.conf;
perl -i -pe 's|(mariadb)(\.service)|postgresql-9.4\2|' something.conf;

The above code did the same thing as sed, but how can I get modified content(" postgresql-9.4.service") to a file or print?

Basically, what I would like to achieve, after running the script, it tells me if it successfully (and what actually replaces), and if not, I will show a message saying that it could not be found and replaced.


Edit: It is
emphasized that I want to get (only-the-) modified content, which indicates the success of my script. Because with perl -i -pe 's/pattern/replace/' fileI could not know whether it will return true or false. Of course, I can just do grep -E "/pettern/"to find out, but that is not a question.

+4
source share
3 answers

This is not so neat in Perl, because you have to explicitly open your log file, but for a single line, which should be in a block BEGIN. But Perl s///returns the number of changes made, so you can check for the truth

, $2 , \2 Perl, 2 Unicode U + 0002 START OF TEXT

perl -i -pe ' BEGIN { open F, ">perl-output.log" } print F $_ if s|(mariadb)(\.service)|postgresql-9.4$2| ' something.conf
+2

, 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

END- , perl , , - die(). ( , exec - ( ).) END - ; : , (LIFO). END perl -c .

, s operator

s/PATTERN/REPLACEMENT/msixpodualngcer

, , , .

+5

, :

if [[ -z $(sed -n 's/mariadb\(\.service\)/postgresql-9.4\1/p' something.conf) ]]; then
    echo nope
fi
0

Source: https://habr.com/ru/post/1622053/


All Articles