1

I have a bash script which uses perl to replace a regex in a configuration file. If someone has manually modified parts of the conf file they shouldn't have the regex may fail because the line it's looking for doesn't exist or no longer matches the regex.

I want to add a quick check to see if a replacement occurred, and if one doesn't occure write some error message to stdout telling them we couldn't do the configuration promised and they need to update the conf file manually.

How can I check rather the perl command was able to successfully find & replace something when I run it?

3

Within perl one might tally the number of substitutions and indicate a failure if the expected number has not been made with the downside of having to maintain the number of subs, risk of false positives, etc

$ (echo cat; echo dog) \
  | perl -ple '$s += s/cat/gato/; $s += s/dog/perro/;' \
    -e 'END { die "incomplete sub" if $s != 2 }'

Or outside write the substituted data out to a new file and confirm that the newfile differs from the original file:

perl ... file > newfile
cmp file newfile && echo >&2 "error unchanged"

The downside of this form is it can only detect if no changes are made, and not when some of the total substitutions fail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.