Error in logic to replace all phrases within an x file using Bash Shell Script

Asked

Viewed 44 times

1

How can I replace all the same phrases within a file, using Bash Shell Script, when receiving the value to be replaced from a variable?

1 - How I would like - but it doesn’t work.:

 txtSalt="frase-que-sera-substituida"

    perl -i -pe'
    BEGIN {
        @chars = ("a" .. "z", "A" .. "Z", 0 .. 9);
        push @chars, split //, "!@#$%^&*()-_ []{}<>~\`+=,.;:/?|";
        sub salt { join "", map $chars[ rand @chars ], 1 .. 64 }
    }
    s/$txtSalt/salt()/ge
    ' meuarquivo.php

2 - How it works - with the phrase applied directly.:

    perl -i -pe'
    BEGIN {
        @chars = ("a" .. "z", "A" .. "Z", 0 .. 9);
        push @chars, split //, "!@#$%^&*()-_ []{}<>~\`+=,.;:/?|";
        sub salt { join "", map $chars[ rand @chars ], 1 .. 64 }
    }
    s/frase-que-sera-substituida/salt()/ge
    ' meuarquivo.php

1 answer

1


Inside simple quotes (') everything is interpreted literally. That is, you need to close the single quotes, put something in double quotes ("), and re-open the single quotes.

'codigoAntes'"$variavel"'codigoDepois'

In your case, I would:

[...]
s/'"$txtSalt"'/salt()/ge
[...]

Keep in mind that concatenating variables to form a Bash command is not good practice, as you are vulnerable in a similar way to a SQL Injection. Of course, in a small script like yours in which the variable is literally set at the top I believe to have no problem.

For further reading, see that answer (in English).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.