LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Help with sed syntax and single quotes (https://www.linuxquestions.org/questions/linux-newbie-8/help-with-sed-syntax-and-single-quotes-4175502614/)

bulldoggk 04-22-2014 03:57 PM

Help with sed syntax and single quotes
 
Hey all,

I've searched a ton on this, but couldn't find what I was hoping to find. I want to use sed to replace some text in a config file. I've used it successfully before in situations without single quotes, but this time single quotes are part of the string that I want to insert into the file.

Here's the command:

Code:

sed -i 's?library_dirs = [?library_dirs = ['$PATH_TO_FTDI', ?g' ./setup.py
What I want is to replace the text "library_dirs = [" in setup.py with "library_dirs = ['$PATH_TO_FTDI', " where the single quotes, comma, and space need to exist and $PATH_TO_FTDI will be replaced with what is stored in that environment variable.

I know the solution requires escaping, and I get that when it comes to, say, directory names with spaces in them (e.g. My\ Whacky\ Folder), but I'm not sure how to do it here.

Thanks,
Gabe

evo2 04-22-2014 04:11 PM

Hi,

instead of escaping the single quotes in your replacement text you can switch to using double quotes in the sed command. You will however need to escape the $ and [. Eg
Code:

sed -i "s?library_dirs = \[?library_dirs = \['\$PATH_TO_FTDI', ?g" ./setup.py
HTH,

Evo2.

bulldoggk 04-22-2014 04:28 PM

That worked almost perfectly, thanks!

The only thing it didn't do is replace $PATH_TO_FTDI with what is actually in that environment variable. PATH_TO_FTDI=/usr/local/include/libftdi1/, and it's that actual path that I want to show up in the setup.py file.

Unless python will see that environment variable as-is, which I guess would be ok too.

evo2 04-22-2014 05:30 PM

Hi,
Quote:

Originally Posted by bulldoggk (Post 5157346)
That worked almost perfectly, thanks!

The only thing it didn't do is replace $PATH_TO_FTDI with what is actually in that environment variable. PATH_TO_FTDI=/usr/local/include/libftdi1/, and it's that actual path that I want to show up in the setup.py file.

Ohh, I had assumed that was the desired effect. In this case don't escape the $. Ie do:
Code:

sed -i "s?library_dirs = \[?library_dirs = \['$PATH_TO_FTDI', ?g" ./setup.py
Quote:

Unless python will see that environment variable as-is, which I guess would be ok too.
No, to get to environment variables in python you need to use the getenv method of the os module. Eg
Code:

import os
print os.getenv('HOME')

Cheers,

Evo2.

bulldoggk 04-22-2014 09:59 PM

Awesome, thanks!

grail 04-23-2014 01:26 AM

Remember to mark as SOLVED once you have a solution.


All times are GMT -5. The time now is 05:07 AM.