0

I want to change some string in file with content in another file

sed -i "s/##END_ALL_VHOST##/r $SERVERROOT/conf/templates/$DOMAIN.conf/g" $SERVERROOT/conf/httpd_config.conf

I need to change string ##END_ALL_VHOST## with content in file httpd_config.conf

Please help :)

3
  • r command doesn't work within substitute command... it applies only to all matching address, for ex: sed '/regex/r file' ... it will add contents of file after the matching line, it cannot be used to replace part of line.. you could delete the matching line if you want.. for ex: sed -e '/regex/r file' -e '/regex/d' Commented Aug 9, 2018 at 3:59
  • Is the marker string ###END_ALL_VHOST### part of line (with other text before or after it) or is it the whole line? The difference matters — if it is a line, it can be handled in sed easily enough; if it is part of line, life is difficult in sed. Commented Aug 9, 2018 at 5:29
  • @jww has downvoted everyone again so I'm upvoting everyone (except myself of course) to compensate. Sigh... Commented Aug 10, 2018 at 14:38

2 Answers 2

1

Here's a way of doing it. Fancify the cat command as needed.

(pi51 591) $ echo "bar" > /tmp/foo.txt
(pi51 592) $ echo "alpha beta gamma" | sed "s/beta/$(cat /tmp/foo.txt)/"
alpha bar gamma
Sign up to request clarification or add additional context in comments.

2 Comments

No, try that when foo.txt contains forward slashes or ampersands or escapes followed by numbers or dollar signs or.....
Of course it doesn't work for every possible combination of chars. For a simple var it works fine. Is it how I'd do it? Prolly not, but for the swapping out a hostname, where slashes and ampersands and escapes followed by numbers or dollar signs are not allowed - works as advertised.
1

sed cannot operate on literal strings so it's the wrong tool to use when you want to do just that, as in your case. awk can work with strings so just use that instead:

awk '
BEGIN { old="##END_ALL_VHOST##"; lgth=length(old) }
NR==FNR { new = (NR>1 ? new ORS : "") $0; next }
s = index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+lgth) }
' "$SERVERROOT/conf/templates/$DOMAIN.conf" "$SERVERROOT/conf/httpd_config.conf"

You may need to swap the order of your 2 input files, it wasn't clear from your question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.