Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SED replace with 'dynamic variable' build from backreference

Tags:

bash

sed

UPDATED

Let's say I have a file with this contents

database_driver="pdo_mysql"
database_host="11.22.33.44"
database_port="3306"


%database_driver%
%database_host%
%database_port%

Now I'd like to replace %database*****% with the content of th corresponding variable, so i would end up with

pdo_mysql
11.22.33.44
3306

I now how to do this line by line, but I'd like to have one sed replace command to replace all values at once

I tried this

sed -r  "s/%(database.*)%/$\1/g" file.yml

I'm trying to create a variable from the second backreference, but this doesn't work, it get this

$database_driver

So I get the name of the variable, not the value

Any ideas?

UPDATE I've got a number of answers but none of them seem to work and they all look very difficult. I'd still like to have an answer to my initial question: Is there a way to make this work

sed -r  "s/%(database.*)%/$\1/g" file.yml

This replaces

%SOMETHING%  into $SOMETHING 

and

%SOMETHING_ELSE%  into $SOMETHING_ELSE.

But I need the VALUE of $SOMETHING and $SOMETHING_ELSE This would be the most ideal solution I guess. Much shorter and more readable the the proposed solutions

like image 357
Harmstra Avatar asked Feb 03 '26 17:02

Harmstra


1 Answers

I would use awk, like this:

awk -F'"| +' '$1=="database_driver="{d=$2}/%database_driver%/{$2=d}1' a.txt

With the help of GNU grep you might even use this:

driver=$(grep -oP 'driver="\K[^"]+' a.txt)
sed "s/%database_driver%/$driver/" a.txt
like image 92
hek2mgl Avatar answered Feb 05 '26 07:02

hek2mgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!