Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a string by the content of a file

I have file A : a nginx config. Somewhere in this file I have {here}

I want to replace that {here} by the content of another file B:

location /blah {
     proxy_pass "https://blah.com";
}

I have tried with sed and awk (gsub) but I have issues with the return/unescaped character.

I found a solution but only works only with pattern, doesn't work with substitution. In this example it will append fileB after my marker instead of replacing it :

sed -i '/{here}/{r fileB
:a;n;ba}' nginx.conf
like image 690
Bastien974 Avatar asked Jan 31 '26 08:01

Bastien974


2 Answers

This should do it:

awk 'NR==FNR { a[n++]=$0; next } 
/{here}/ { for (i=0;i<n;++i) print a[i]; next }
1' fileB fileA

Build an array containing all of the lines of the file containing the replacement. When the pattern is matched in the second file, print out all of the lines. Otherwise, the 1 at the end means that the original lines are printed.

As Ed has rightly pointed out, the loop initialiser was wrong. I've changed it to i=0 so the first line is printed. Also, this replaces the whole contents of the line containing {here}, which may or may not be what you need.

To overwrite the original file, you can do:

awk '...' fileB fileA > tmp && mv tmp fileA
like image 115
Tom Fenech Avatar answered Feb 02 '26 08:02

Tom Fenech


All you need is:

awk 'NR==FNR{rep=(NR>1?rep RS:"") $0; next} {gsub(/{here}/,rep)}1' fileB nginx.conf

assuming fileB doesn't contain &s as they'd be interpreted by the replacement operation as the RE-matching string. If it does then use index() and substr() in a loop.

If {here} is the ONLY thing on the line, tell us about that as it makes the problem a bit simpler.

like image 31
Ed Morton Avatar answered Feb 02 '26 08:02

Ed Morton



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!