Avishek2585835
Avishek2585835

Reputation: 91

using sed to replace env file values

I am having a .env file like:

export TENANT_SSH_USER_NAME=xxxx
export TENANT_SSH_KEY="ssh-ed25519 <string of alphanumeric chars>  uname@hostname" 
export TENANT_LOAD_BALANCERS=1

I wanted to update the SSH Key value with a new one.

newkey=$(echo $(cat ~/.ssh/new.pub))

so the regex i was using is: ssh([^"]*)

but to replace the value in the same file, I wanted to use sed.

I tried, sed -i.bak 's/ssh\([^\"]\*\)/\"$newkey\"/g' $1-where $1 is the input .env file

sed -i '' -E 's/ssh\([^\"]\*\)/\"$newkey\"/g' $1

sed -i '' -E 's/ssh\([^\"]\*\)/\"$newkey\"/g' $1

sed -i '' -E 's/ssh\([^\"]\*\)/$newkey/g' $1

code:

input_file=$1
old_key=$(grep TENANT_SSH_KEY= $input_file | cut -d '=' -f2)
echo old key...
echo $old_key

#final regex: ssh([^"]*)


newkey=$(echo $(cat ~/.ssh/new.pub))
echo new key...
echo $newkey

echo post processing...
sed -i  '' -E 's/ssh\([^\"]\*\)/$newkey/g' $1
cat $1 | grep ssh-ed25519

output:

./ssh_key.sh myenv.env
old key...
"ssh-ed25519 <string> <uname1>@<host1>"
new key...
ssh-ed25519 <string> <uname2>@<host2>
post processing...
export TENANT_SSH_KEY="ssh-ed25519 <string> <uname1>@<host1>"

Please help in identifying the mistake in sed(possibly?). Other suggestions to solve this problem is also welcome. I am working on a mac(10.14.5), but want to make the solution work for mac and linux both.

Thanks.

Upvotes: 1

Views: 2621

Answers (1)

sqek
sqek

Reputation: 136

sed -i "s/ssh[^\"]*/$newKey/" $1 seems to work in bash for me

I think the problem with your tries is that you don't need to escape the double quotes if you're putting the substitution string in single quotes (so you'd do sed 's/ssh[^"]*/etc' without the backslash, and if you use single quotes then the variable $newkey doesn't get expanded so you'd end up with export TENANT_SSH_KEY="$newKey"

Also the brackets in your sed command aren't needed here

Upvotes: 2

Related Questions