How to make 'sed' to skip commented lines starting with '#'?

PeterBSD

New Member
Joined
Jul 8, 2020
Messages
14
Reaction score
1
Credits
173
I'm using 'sed' to modify config files.

Specifically, I'm using 'sed' to search lines with "</Direcotry>" and insert lines above it. My example command is as below (test.conf file contains multiple sections of <Directory ....>....</Directory>-

sudo sed –i.bak ‘/<\/Directory>/i \\t<Test1>\n\t\tThis is test1\n\t<\/Test1>’ test.conf

test.conf is customed conf file (see below) and -i.bak will create backup of original file so you can retry the command with.

This command works on my file but it also modify the commented section(s), how can I make the command to skip the commented lines (e.g. [#</Directory>] or [# </Directory>])?

You can grab any httpd.conf file with '<Directory ...> sections or create your own one like below -

<Directory /opt/test>
Some text
</Direcotry>
#<Directory /opt/test>
# Some text
#</Direcotry>
<Directory /opt/test>
Some text1
</Direcotry>


Expected result (after sed command works completely)

<Directory /opt/test>
Some text
<Test1>
This is test1
</Test1>
</Direcotry>
#<Directory /opt/test>
# Some text
#</Direcotry>
<Directory /opt/test>
Some text1
<Test1>
This is test1
</Test1>
</Direcotry>

Thanks!
 


If the </directory> tag is the very first thing in the line, then you could ignore the commented lines by using the "start of line" anchor ^ in your search regex.
e.g.
Bash:
sudo sed -i.bak '/^<\/Directory>/i \\t<Test1>\n\t\tThis is test 1\n\t<\/Test1>' test.conf

That way, any line that starts with </Directory> will be matched. Any lines that start with anything else will be ignored, including commented-out lines.

If you have any whitespace before the </Directory> tag, you may need to modify the regex to ignore any amount of whitespace at the start of the line, because otherwise lines with whitespace at the start will be ignored too.
So, if this is the case, make the necessary changes to the regex after the anchor ^ and before the start of the </Directory> tag.
 

Members online


Top