Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Commenting out lines in a file using a bash script

I am trying to modify a certain file on my linux machine in a script. The file is the /etc/pam.d/login file. The issue is that the contents of the file are,

# Prints the message of the day upon succesful login. 
# (Replaces the `MOTD_FILE' option in login.defs)
# This includes a dynamically generated part from /run/motd.dynamic
# and a static (admin-editable) part from /etc/motd.
session    optional   pam_motd.so  motd=/run/motd.dynamic noupdate
session    optional   pam_motd.so

And I need to comment out the second session line in this file but when I go to string match the result is as follows (I am using SED to do so for those interested).

# Prints the message of the day upon succesful login.
# (Replaces the `MOTD_FILE' option in login.defs)
# This includes a dynamically generated part from /run/motd.dynamic
# and a static (admin-editable) part from /etc/motd.
#session    optional   pam_motd.so  motd=/run/motd.dynamic noupdate
#session    optional   pam_motd.so

Because the first line matches the condition as well. How would I make sure that the whole line matches "session optional pam_motd.so" and not just a certain part of it.

Thanks!

like image 460
user2569803 Avatar asked Jan 17 '17 20:01

user2569803


1 Answers

You need to use line start (^) and line end ($) in your regex. Like:

sed -i '/^session    optional   pam_motd\.so$/s/^/#/' /path/to/file
like image 57
Grisha Levit Avatar answered Sep 17 '22 04:09

Grisha Levit