【问题标题】:Commenting out lines in a file using a bash script使用 bash 脚本注释掉文件中的行
【发布时间】:2017-06-02 01:09:33
【问题描述】:

我正在尝试在脚本中修改我的 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

我需要注释掉这个文件中的第二个会话行,但是当我去字符串匹配时,结果如下(我正在使用 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

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

谢谢!

【问题讨论】:

    标签: linux bash replace sed


    【解决方案1】:

    您需要在正则表达式中使用行首 (^) 和行尾 ($)。喜欢:

    sed -i '/^session    optional   pam_motd\.so$/s/^/#/' /path/to/file
    

    【讨论】:

      【解决方案2】:

      使用^$ 锚来限制你的匹配:

      sed 's/\(^session    optional   pam_motd.so$\)/#\1/' file > file.new
      

      【讨论】:

        猜你喜欢
        • 2021-11-28
        • 1970-01-01
        • 1970-01-01
        • 2010-11-29
        • 2017-05-02
        • 2017-02-13
        • 2016-11-03
        • 2013-08-23
        • 1970-01-01
        相关资源
        最近更新 更多