在bash脚本中注释掉文件中的行

use*_*803 4 linux bash replace sed

我试图在脚本中修改我的linux机器上的某个文件.该文件是/etc/pam.d/login文件.问题是文件的内容是,

# 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
Run Code Online (Sandbox Code Playgroud)

我需要注释掉这个文件中的第二个会话行,但是当我去字符串匹配时,结果如下(我正在使用SED为那些感兴趣的人这样做).

# 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
Run Code Online (Sandbox Code Playgroud)

因为第一行也符合条件.我如何确保整行与"会话可选pam_motd.so"匹配,而不仅仅是它的某个部分.

谢谢!

Gri*_*vit 9

你需要在正则表达式中使用line start(^)和line end($).喜欢:

sed -i '/^session    optional   pam_motd.so$/s/^/#/' /path/to/file
Run Code Online (Sandbox Code Playgroud)