16

I am trying to use sed to replace a line with spaces with a defined variable.

For example,

I want to replace 'a dumb string' with $lan, and lan="~/afile.py

I assumed the line would be

sed "s/a dumb string/$lan/g" file.txt

but this leave the 'a dumb string' part blank in the file.txt.

My problem seems simple enough. Any help is much appreciated.

4
  • 2
    Are you sure that you've set the variable Ian? What happens when you run echo "<<$Ian>>"? Commented Mar 5, 2013 at 23:40
  • 2
    Now is it a dump string or a dumb string?! Commented Mar 5, 2013 at 23:42
  • ha ha, it's a dumb string. Sorry, I'll correct the typo Commented Mar 5, 2013 at 23:49
  • @ruakh the $lan is set correctly, but I found the root of the problem. $lan is a file name and has slashes in it. I'll clarify the question. Commented Mar 5, 2013 at 23:52

3 Answers 3

22

I determined that because my @lan variable has slashes in it, I need to use the sed command using :

For example

sed "s:a dumb string:$lan:g" file.txt

This is probably a novice mistake, but I'm not that familiar with sed. Thank you for your help.

Sign up to request clarification or add additional context in comments.

Comments

19

sed is not aware that you're passing a variable -- it'll be interpreted as just another part of your regex. If your substitution contains slashes, the easiest thing to do is use an alternate separator char, like this:

sed "s|a dumb string|$lan|g" file.txt

Comments

8

Sometime space in search string does not work so needed to use [[:space:]] in centos.

    sed -i 's/User[[:space:]]daemon/User apache/' httpd1.conf

1 Comment

I would have cried for days if it wasn't for your answer here!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.