Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting text in a file from a variable

I have a file that looks something like this:

ABC
DEF
GHI

I have a shell variable that looks something like this:

var="MRD"

What I want to do, is to make my file look like this:

ABC
MRD
DEF
GHI

I was trying to do this:

sed -i -e 's/ABC/&$var/g' text.txt 

but it only inserts $var instead of the value. I also tried this:

sed -i -e 's/ABC/&"$var"/g' text.txt 

but that didn't work either. Any thoughts?

Thanks!

like image 201
user754905 Avatar asked Mar 08 '26 19:03

user754905


1 Answers

See if this works.

var="MRD"
sed 's/ABC/&\n'"${var}"'/' text.txt

EDIT

We can use any character instead of /. So if we expect it to be in the search or replace expression, use |

var="</stuff>"
sed 's|ABC|&\n'"${var}"'|' text.txt
like image 133
amit_g Avatar answered Mar 11 '26 08:03

amit_g



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!