Sureshchandra Jarugula
Sureshchandra Jarugula

Reputation: 123

un-comment a specific line in a file

I have a file which contains the line below.

#LoadModule status_module "${PRODUCT_HOME}/modules/mod_status.so"

I want one sed to un-comment the line from above and one command to comment it. I tried the command below.

sed "/^#/LoadModule status_module "${PRODUCT_HOME}/modules/mod_status.so"/LoadModule status_module "${PRODUCT_HOME}/modules/mod_status.so"/g" file.txt

Upvotes: 0

Views: 72

Answers (1)

Socowi
Socowi

Reputation: 27215

One problem is, that things like " and ${PRODUCT_HOME} are interpreted by the shell. You have to escape them properly so that they reach sed as literals. Also / is is treated specially by sed (in the way you use it) and has to be escaped too.

We will use a variable for escaping and making things easier to read:

line='LoadModule status_module "${PRODUCT_HOME}/modules/mod_status.so"'

Now to the sed command. If you want to replace something, the syntax is s/search/replace/. The string search will be replaced by replace. Instead of s/search/replace/ we can also write s:search:replace:, allowing us to use the / inside the search and replace text.

uncomment

 sed "s:#$line:$line:"

comment

sed "s:$line:#$line:"

Upvotes: 2

Related Questions