Replace occurrences of a string in file with different bytes of entropy each

rypel :

On Linux, I need to programmatically replace placeholder strings such as <SECRET> in a .env file like this:

KEY=<SECRET>
ANOTHER_VARIABLE=another-value
# here's a comment
PASSWORD=<SECRET>

The caveat is, that each occurrence of this placeholder must be replaced with a different instantiation of Base64 encoded randomness - e.g. from OpenSSL, since it's readily available on many Linuxes.

Reading this answer, I tried this with GNU sed 4.8:

sed -i '0,/<SECRET>/ s__'$(openssl rand -base64 42)'_' .env

(In the substitution part the alternative delimiter _ was chosen, because the Base64 encoded bytes can contain / or + characters and would otherwise clash when inadvertently used as delimiters.)


This works for single replacements, one call at a time.

But sed's return code is always 0, even when all occurrences of the regex have been consumed and replaced...

Question: Is there a way to make sed return a non-zero code when placeholders have been exhausted?

(If this can't be done with sed, I'm happy for any solution with awk or similar.)

Quasímodo :

Instead of sed, you could use grep:

grep '<SECRET>' .env

From man grep:

EXIT STATUS

Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred.

If the return value is 0, then apply your sed command to perform the substitution.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=18233&siteId=1