我有一个包含以下输入的文件。
----------
ID: alternatives_create_editor
Function: alternatives.install
Name: editor
Result: None
Comment: Alternative will be set for editor to /usr/bin/vim.basic with priority 100
Started: 10:45:49.115459
Duration: 0.78 ms
Changes:
----------
ID: hosts_1
Function: host.present
Name: ip6-allnodes
Result: None
Comment: Host ip6-allnodes (ff02::1) already present
Started: 10:45:49.127667
Duration: 1.117 ms
Changes:
----------
ID: sfrsyslog_fix_logrotate
Function: file.managed
Name: /etc/logrotate.d/rsyslog
Result: None
Comment: The file /etc/logrotate.d/rsyslog is set to be changed
Started: 10:45:50.771278
Duration: 12.751 ms
Changes:
----------
我的目标是删除 Comment: contains 已经存在的整个部分。
我试过,grep -B 5 -A 4 'already present' FILE1 > FILE2
。
然后,
diff -y FILE1 FILE2 | grep '<' | sed 's/
在此输出中我得到如下所示,
ID: alternatives_create_editor
Function: alternatives.install
Name: editor
Result: None
Comment: Alternative will be set for editor to /usr/bin/
Started: 10:45:49.115459
Duration: 0.78 ms
Changes:
----------
ID: sfrsyslog_fix_logrotate
Function: file.managed
Name: /etc/logrotate.d/rsyslog
Result: None
Comment: The file /etc/logrotate.d/rsyslog is set to be
Started: 10:45:50.771278
Duration: 12.751 ms
Changes:
----------
问题是Comment: section
没有给出完整的线路。请帮忙。谢谢
答案1
更直接的是使用单个 GNU awk 命令:
awk 'BEGIN{RS=ORS="----------\n"};!/Comment:[^\n]*already present/' file
它只是将记录分隔符设置为十虚线,如果记录包含Comment:[^\n]*already present
,它会抑制该记录。[^\n]*
表示“不是换行符”,因此如果记录有already present
inChanges:
但不包含 in ,则不会抑制该记录Comment:
。
输出:
----------
ID: alternatives_create_editor
Function: alternatives.install
Name: editor
Result: None
Comment: Alternative will be set for editor to /usr/bin/vim.basic with priority 100
Started: 10:45:49.115459
Duration: 0.78 ms
Changes:
----------
ID: sfrsyslog_fix_logrotate
Function: file.managed
Name: /etc/logrotate.d/rsyslog
Result: None
Comment: The file /etc/logrotate.d/rsyslog is set to be changed
Started: 10:45:50.771278
Duration: 12.751 ms
Changes:
----------
如果您没有 GNU awk,则上述内容可能不起作用,因为 POSIX 没有定义多字符记录分隔符的行为。所以我留下了这个便携式替代方案:
awk '/Comment:.*already present/{p=1}
/^-{10}$/{
if(p!=1){printf "%s",lines}
p=0
lines=""
}
{lines=lines $0 RS}
' file
答案2
另一个awk
解决方案:
awk 'BEGIN{RS=ORS="----------\n"} $0 !~ /already present/' file