Bash - Replace a text with a variable containing new lines character
Hey All,
I am trying to replace a variable in sed, usually, it can be done by double quotes but my variable has new lines characters and backslashes which somehow is not working. This is a sample variable Code:
# echo $CLIENT_KEY Code:
# cat myfile |
I'm not sure how it can be done with the multiple line replacement. It's easy with Perl 5 however.
Code:
cat myfile | perl -p -e "s|CLIENT_KEY|${CLIENT_KEY}|" |
#1 this appears to be a SED question, not a BASH question, so your title is misleading.
#2 for what you want to do, I am not sure that SED is the correct tool. PERL would be optimal, GSAR would serve. Could we have some detail about what you are really trying to achieve, and why you selected SED (not BASH) to approach the problem? |
The two character text string "\n" is just that - not a newline unless interpolated somehow. Perl, sed would make no difference.
Embedding 0x0A might work. Untested. |
Help us to help you. Start by constructing a simplified InFile such as ...
Code:
--BEGIN PRIVATE KEY--\nAAA\nBBB\nCCC\n\n--END PRIVATE KEY-- These files will facilitate understanding and give us an example for testing. Daniel B. Martin . |
Quote:
Thanks, but this did not work, it interpolates "\n" into new lines. I've tried with perl v5.16.3 |
Quote:
I deliberately chose bash and not sed, as I am on bash shell and (as you correctly hinted) that sed may not be the correct tool. I have tried sed, because that was the first tool which came into my mind for replacing text and which has been working great for all my needs so far. |
With this InFile ...
Code:
ABC Code:
str="--BEGIN PRIVATE KEY--\nAAA\nBBB\nCCC\n\n--END PRIVATE KEY--" Code:
InFile ... . |
Quote:
|
... Or maybe this is what you want ...
With this InFile ... Code:
ABC Code:
str="--BEGIN PRIVATE KEY--\nAAA\nBBB\nCCC\n\n--END PRIVATE KEY--" Code:
ABC\n--BEGIN PRIVATE KEY--\nAAA\nBBB\nCCC\n\n--END PRIVATE KEY--\nDEF . |
I think the two characters \ and n should be kept here. But a RE interprets it.
How about bash (as the title already suggests)? Code:
str="--BEGIN PRIVATE KEY--\nAAA\nBBB\nCCC\n\n--END PRIVATE KEY--" |
To prevent things like slash codes from being interpreted by the shell/command line and programs you would use single quotes instead of doble quotes. Somehow I doubt if that is really what you want. Normally a key file will contain embedded newlines at those locations. Why does the interpretation of the newline concern you?
|
Quote:
Thanks everyone for your time. |
Quote:
Code:
str='...' Indeed within " " the shell does special treatment of $ and " and ` characters (and allows \ escape of them, therefore the \ character is a bit special, too). BTW once stored in a variable, the shell does not do further special treatment of "$str" |
I have also found a neat python solution for the same
Code:
f = open(file, 'r') |
All times are GMT -5. The time now is 12:15 PM. |