How to comment a specific line of a file?

Hi,

I need to comment out (insert # in the front of a line) a line that has entry Defaults requiretty using command-line as I need to do this on hundreds of servers.

From
Defaults requiretty

To
#Defaults requiretty

I tried something like below but no luck: Please advise, thanks

awk '/requiretty/{print "#",$0}1' /etc/sudoers >/etc/sudoers.new

Hello prvnrk,

Following may help you in same.(not tested though)

awk '/Defaults requiretty/ {$0="#"$0} 1' file_name > Output_file_name

Thanks,
R. Singh

1 Like

Thanks RavinderSingh,

Unfortunately your solution did NOT work if I used as it is.

[root@test_srvr tmp]# cat test_file
Defaults    requiretty
# changed in order to be able to use sudo without a tty. See requiretty above.
[root@test_srvr tmp]# awk '/Defaults requiretty/ {$0="#"$0} 1' test_file
Defaults    requiretty
# changed in order to be able to use sudo without a tty. See requiretty above.
[root@test_srvr tmp]# gawk '/Defaults requiretty/ {$0="#"$0} 1' test_file
Defaults    requiretty
# changed in order to be able to use sudo without a tty. See requiretty above.
[root@test_srvr tmp]#

But it worked if I use only requiretty but it's adding # to all the lines that has requiretty . I think it's due to variable spaces between Defaults and requiretty . Is there any way to discard number of spaces between them and check?

[root@test_srvr tmp]# gawk '/requiretty/ {$0="#"$0} 1' test_file
#Defaults    requiretty
## changed in order to be able to use sudo without a tty. See requiretty above.

Hello prvnrk,

You can use following.

awk '/^Defaults.*requiretty$/ {$0="#"$0} 1' file_name

It is only for lines which are starting from Defaults and ending for requiretty. If this doesn't fulfills your requirement kindly let us know the complete request.

Thanks,
R. Singh