Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variable with sed

Tags:

bash

sed

First of all i apologise in case this has been answered before but i couldn't solve my problem.

I need to search a pattern and then replace it with a line of text comprising of both text and variable.Btw i am using bash..

say

$var = "stacko.ver/rulz=" **Note: $var contain double quotes & = & a dot and /**

i want to so the follow 1.Search for ;te.xt = Note: The value to be search contain ; & = and a dot

2.Replace it with

textnum=$var

Of course $var should be replaced with its actual value

My attempts

sed -i "s/;te.xt =/textnum=$var/" file
sed -i "s/;te.xt =/textnum="$var"/" file
sed -i "s/";te.xt ="/"textnum=$var"/" file

None of these actually worked , either sed giving me an error or the value of $var not shown in file

Thanks for the help

Regards

like image 840
user2650277 Avatar asked Feb 22 '26 21:02

user2650277


1 Answers

Quoting doesn't help since this is a sed issue, not a bash issue. Just pick a sed s-expression delimiter that doesn't appear in your text:

sed -i "s|;te.xt =|textnum=$var|" file

You can pick any delimiter for s that doesn't appear in your input. sed -e 'streetlight' is a perfectly valid sed command.

like image 100
that other guy Avatar answered Feb 24 '26 16:02

that other guy



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!