Itai Ganot
Itai Ganot

Reputation: 6305

Sed: How to replace a string which includes multiple special characters?

I'm trying to comment a line in /etc/sudoers through a shell script. That's the relevant line I'd like to edit:

# grep '\!requiretty' /etc/sudoers
Defaults:nagios !requiretty

But it seems like the pattern I'm using with sed is incorrect, my tries:

# sed -i 's/^Defaults\:nagios$/#Defaults:nagios !requiretty/g' /etc/sudoers
# sed -i 's/^Defaults:nagios$/#Defaults:nagios !requiretty/g' /etc/sudoers
# sed -i 's/^Defaults:nagios$/#Defaults:nagios !requiretty/g' /etc/sudoers
# sed -i 's/^Defaults:nagios$/\#Defaults:nagios !requiretty/g' /etc/sudoers
# sed -i 's/^Defaults:nagios$/\#Defaults:nagios \!requiretty/g' /etc/sudoers
# sed -i 's/^Defaults:nagios$/^#Defaults:nagios !requiretty/g' /etc/sudoers
# sed -i 's/^Defaults\:nagios$/^#Defaults:nagios !requiretty/g' /etc/sudoers
# sed -i 's/^Defaults\:nagios$/#Defaults:nagios \!requiretty/g' /etc/sudoers

None of the above worked...

Can someone please assist me with the correct regex?

Thanks in advance

Upvotes: 0

Views: 335

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191749

Well ... sudoers is not meant to be writable by anyone -- even root. You're supposed to edit it with the visudo command instead for security reasons.

I think you might have it backwards though since the first part of the sed substitution is the find. The second part is the replacement. So you would want to do something like:

sed -i 's/^Defaults:nagios !requiretty$/#Defaults:nagios/'

This will also remove the requiretty. If all you want is to add the # you could just do:

sed -i 's/^Defaults:nagios !requiretty$/#&/'

Upvotes: 1

Related Questions