I need to revoke the sudo access to the user using sed in scripts.
I want to comment the user only if the line contains /bin/su - root
Let us consider the file as below, in which I have to comment only the first line.

mindadmin  ALL = NOPASSWD: /bin/su - root
mindadmin  ALL = NOPASSWD: /bin/ifconfig

I have used sed commands as below:

sed -e 's/minadmin[\s]+ALL[\s]+=[\s]+NOPASSWD:[\s]+/bin/su - root/#mindadmin  ALL = NOPASSWD: /bin/su - root/g' /etc/sudoers 

But it is not working. Is there any syntax error in it?


There are two problems, the first is that your sudoers has mindadmin and your pattern minadmin (without the d).

The second problem is in the /s of /bin/su, you have to escape these within the regex:

sed -e 's/mindadmin[\s]+ALL[\s]+=[\s]+NOPASSWD:[\s]+\/bin\/su - root/#mindadmin  ALL = NOPASSWD: \/bin\/su - root/g' /etc/sudoers

otherwise they end the pattern.

You can also shoose another delimiter instead of /, as long as that doesn't occur in the file, you don't have to escape it.

 sed  '/\/bin\/su - root/ s/^/#/'  filename

It locates the lines, in the filename, containing /bin/su - root, and add the comment(#) at the beginning of the line (^).

Add -i option in sed to effecting to file.

  • let substitute / by other symbol and you needn't to escape / in the pattern. For example \%/bin\su - root% – Costas Nov 6 '14 at 12:52

If you want to comment out all lines which contain /bin/su - root at the end of the line, then you can simplify your sed expression:

sed 's/.*\/bin\/su - root$/#&/'

Or, even simpler

sed 's,.*/bin/su - root$,#&,'

To comment out all lines which contain /bin/su - root anywhere in the line:

sed 's,.*/bin/su - root,#&,'

As & is replaced with the whole matching pattern, here another solution:

sed -i 's,.*/bin/su\s\+-\s+root,#&,' /etc/sudoers

/ is replaced by a different separator so you do not need to escape it. The pattern is also more flexible if the spacing after the su command is different.

If it should only change the mindadmin user:

sed -i 's,^mindadmin\s.*/bin/su\s+-\+root,#&,' /etc/sudoers

The flag -i applies directly the change to the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.