Saturday, February 19, 2022

[SOLVED] Replace content in file using bash

Issue

I am looking to replace the line export KEY_COUNTRY="US" with the data read in the variable $COUNTRY in the file /etc/openvpn/easy-rsa/vars

In my previous builds which I used with CentOS6, i used the command replace which is bundled with mysql-server. But now that function is no longer available, i am looking for ideas on alternate command to replace the data.

Thanks in advance.


Solution

You can use sed, but keep in mind that it can fail if $COUNTRY contrains control characters.

sed -i 's/KEY_COUNTRY="US"/KEY_COUNTRY="'"$COUNTRY"'"/' file

Using Perl would be safer, as it doesn't interpret variable contents as part of the syntax:

perl -i -pe 's/KEY_COUNTRY="US"/KEY_COUNTRY="$ENV{COUNTRY}"/' -- file

$COUNTRY must be accessible in the perl process, i.e. you need to export it or assign to it

COUNTRY=$COUNTRY perl ...


Answered By - choroba
Answer Checked By - Willingham (WPSolving Volunteer)