Reputation: 4325
I have figured out and tried replacing strings with the help of gsed -i
command like this:
gsed -i 's/sdkUniqueKey=""/sdkUniqueKey="123"/g' AppConstants.txt
Now I want to do the same operation on another string in my file but as my question states, I need to copy the contents from a different file first and then replace a string, something like:
gsed -i 's/sdkPrivateKey=""/sdkPrivateKey="contentsCopiedFromAnotherFile"/g' AppConstants.txt
One more thing, the contents (to be copied), have next line and white space in it, which I would like to remove before copying. Also it has backslash and forward slashes, hope they don't create any issues while replacing the content). Here is what I am trying to copy:
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDNGillPEfz8d7W
0fyJejF9AYeo8OowcdOcxrpzs4IiXCwPEP1MOHAaOwGTdMwSAeQjw9WOYpE1q+DU
I+Zhh4DVUR8dIdYQtXe+oK/QfhVQMJ3AjTKRvhUmFciGwxXlnLBIkN/ePplNdq9Z
Y5DrSR0lE8X2dD+ZRAkQRpsY8TE48b9f443sbsU4sMvNaxd2XTxe2TLYRvB00w6Q
3lqZiKLzttINBCPoCjhJwBdhcF/LHsCmYhfElPqJxH27BTGBOnbICdmazdnChXQg
3hhsbJmnNDe17Spw0lY
-----END PRIVATE KEY-----
I am able to copy the contents of a file into a variable as well:
contents ="`cat fileToBeRead`"
All I need is to remove white spaces and new lines from this string and use this "contents
" variable in my gsed
command
Upvotes: 1
Views: 2219
Reputation: 1459
If I have properly understood your question, the following should do the trick:
#!/bin/bash
fileToBeRead="key.txt" #Whatever
var=$(tr -d '[:blank:]\n' < $fileToBeRead)
sed -i "s#sdkPrivateKey=\"\"#sdkUniqueKey=\"$var\"#g" AppConstants.txt
Since the key contains backslashes/slashes you should use a different separator for sed (e.g. #) or the sentence will be misparsed.
EDIT:
KEY="$var" perl -pi -e 's/sdkPrivateKey=""/sdkUniqueKey="$ENV{KEY}"/g' AppConstants.txt
perl
can be used instead of sed
in order to avoid sed
's separator issues. Check out @DennisWilliamson's comment below.
Upvotes: 3