sed +在匹配的单词后面添加新行,但如果行存在则忽略



我们创建了下面的sed行,以便在mached word(在redhat 7上)后面添加行。X台机器)

sed -i '/[Service]/a MemoryAccounting=yesnMemoryCurrent=8192000nMemoryLimit=8192000' /lib/systemd/system/rsyslog.service

更新前的文件示例

cat /lib/systemd/system/rsyslog.service
[Unit]
Description=System Logging Service
;Requires=syslog.socket
Wants=network.target network-online.target
After=network.target network-online.target
Documentation=man:rsyslogd(8)
Documentation=http://www.rsyslog.com/doc/
[Service]
Type=notify
EnvironmentFile=-/etc/sysconfig/rsyslog
ExecStart=/usr/sbin/rsyslogd -n $SYSLOGD_OPTIONS
Restart=on-failure
UMask=0066
StandardOutput=null
Restart=on-failure
[Install]
WantedBy=multi-user.target
;Alias=syslog.service
sed 更新后的文件示例
cat /lib/systemd/system/rsyslog.service
[Unit]
Description=System Logging Service
;Requires=syslog.socket
Wants=network.target network-online.target
After=network.target network-online.target
Documentation=man:rsyslogd(8)
Documentation=http://www.rsyslog.com/doc/
[Service]
MemoryAccounting=yes
MemoryCurrent=8192000
MemoryLimit=8192000
Type=notify
EnvironmentFile=-/etc/sysconfig/rsyslog
ExecStart=/usr/sbin/rsyslogd -n $SYSLOGD_OPTIONS
Restart=on-failure
UMask=0066
StandardOutput=null
Restart=on-failure
[Install]
WantedBy=multi-user.target
;Alias=syslog.service

现在的问题是当我们再次运行sed行时我们会得到重复的

[Service]
MemoryAccounting=yes
MemoryCurrent=8192000
MemoryLimit=8192000
MemoryAccounting=yes
MemoryCurrent=8192000
MemoryLimit=8192000

当行已经存在时,有什么建议如何忽略编辑?

指出:

为了完成服务更新,我们需要做以下事情:

systemctl daemon-reload
systemctl restart rsyslog.service

应该可以了

sed -i.SAVED '/[Service]/N;
s/n/ /;
/[Service] Type=notify/c
[Service]
MemoryAccounting=yes
MemoryCurrent=8192000
MemoryLimit=8192000
Type=notify
/[Service] M.*/s/ /n/
' /lib/systemd/system/rsyslog.service

它使用N连接行,用空格检查nl是否与原始行匹配。

还保存了原始文件,以防万一。

使用sed

$ sed -Eei.bak '/[service]/I{n;/^memoryaccounting/I!{i MemoryAccounting=yesnMemoryCurrent=8192000nMemoryLimit=8192000' -e '}}' input_file
[Unit]
Description=System Logging Service
;Requires=syslog.socket
Wants=network.target network-online.target
After=network.target network-online.target
Documentation=man:rsyslogd(8)
Documentation=http://www.rsyslog.com/doc/
[Service]
MemoryAccounting=yes
MemoryCurrent=8192000
MemoryLimit=8192000
Type=notify
EnvironmentFile=-/etc/sysconfig/rsyslog
ExecStart=/usr/sbin/rsyslogd -n $SYSLOGD_OPTIONS
Restart=on-failure
UMask=0066
StandardOutput=null
Restart=on-failure
[Install]
WantedBy=multi-user.target
;Alias=syslog.service

如果[Service]后面紧跟着以MemoryAccounting=开头的行,则此sed命令将跳过插入文本。

sed -i.orig '
/[Service]/{
n
/^MemoryAccounting=/b
i
MemoryAccounting=yes
MemoryCurrent=8192000
MemoryLimit=8192000
}' rsyslog.service

最新更新