0

我刚开始使用 Linux,我需要注释/取消注释 .yml 文件的某些行。我已经搜索了文档,并在这里通过不同的帖子搜索了这个,例如:comment a line with sed

我需要从这里注释第 1 行和第 3 行:

output.elasticsearch:
  # Array of hosts to connect to.
  hosts: ["localhost:9200"]

并从此处取消注释第 1 行和第 3 行:

#output.logstash:
  # The Logstash hosts
  #hosts: ["localhost:5044"]

我使用了这些命令:

sudo sed -i '/output.elasticsearch/s/^/#/g' /etc/filebeat/filebeat.yml
sudo sed -i '/["localhost:9200"]/s/^/#/g' /etc/filebeat/filebeat.yml
sudo sed -i '/output.logstash/s/^#//g' /etc/filebeat/filebeat.yml
sudo sed -i '/["localhost:5044"]/s/^  #//g' /etc/filebeat/filebeat.yml

但是,虽然这适用于每个块的第 1 行,但它不适用于第 3 行,其中 # 符号前有空格,我不知道如何更改

4

2 回答 2

1

这可以通过在示例“filebeat.yml”文件上执行三个 sed 命令来实现

 sed -Ei '/^output.elasticsearch:$/,/^.*hosts: \["localhost:9200"\]$/{s/(^.*$)/#\1/}' filebeat.yml

第一个命令从以“output.elasticsearch”开头和结尾的行搜索到包含“hosts: ["localhost:9200"]”的行。对于该子集搜索,它会搜索完整的行 (^.*$) 和然后用 # (#\1) 前缀替换此行

 sed -Ei '/(^.*#hosts: \["localhost:5044"\]$)/{s/(^.*#)(.*$)/  \2/g}' filebeat.yml
 

第二个命令搜索 log stash hosts 行并将找到的行分成两部分,第一部分是行的开头到 # ,然后第二部分是该行的其余部分。然后,我们将这一行替换为第二部分,创建一个不带 # 的行,但根据 yaml 语法的要求添加了 2 个空格。

sed -Ei '/(^#output.logstash:$)/{s/(^.*#)(.*$)/\2/g}' filebeat.yml

第三个命令遵循与第二个相同的逻辑,但这次不保留任何空格

于 2020-11-24T12:29:41.237 回答
1

以下代码:

sed '
    /output\.elasticsearch/s/^/#/;
    /\["localhost:9200"\]/s/^[[:space:]]*/&#/;
    /output\.logstash/s/^#//;
    /\["localhost:5044"\]/s/^\([[:space:]]*\)#/\1/;
' <<EOF
output.elasticsearch:
   # Array of hosts to connect to.
   hosts: ["localhost:9200"]
#output.logstash:
   # The Logstash hosts
   #hosts: ["localhost:5044"]
EOF

输出:

#output.elasticsearch:
   # Array of hosts to connect to.
   #hosts: ["localhost:9200"]
output.logstash:
   # The Logstash hosts
   hosts: ["localhost:5044"]

[(and .) 在正则表达式中是特殊的 - 转义它们。为了保持意图,我将空格与[[:space:]]*. 应用全局标志是没有意义的g,如果它无论如何都将是一个替换。

还有一个整洁的oneliner,因为为什么不:

sed -i '/output\.elasticsearch/s/^/#/; /\["localhost:9200"\]/s/^[[:space:]]*/&#/; /output\.logstash/s/^#//; /\["localhost:5044"\]/s/^\([[:space:]]*\)#/\1/;' file_path
于 2020-11-24T12:33:20.423 回答