我刚刚开始使用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行,其中get在#符号之前有空格,我不知道如何更改
发布于 2020-11-24 20:29:41
这可以通过在示例"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-24 20:33:20
以下代码:
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"][ (和.)在正则表达式中是特殊的-对它们进行转义。为了保留原样,我将空白与[[:space:]]*进行了匹配。应用g全局标志是没有意义的,如果它无论如何都是一个替代。
和一个整洁的眼线笔,因为为什么不:
sed -i '/output\.elasticsearch/s/^/#/; /\["localhost:9200"\]/s/^[[:space:]]*/&#/; /output\.logstash/s/^#//; /\["localhost:5044"\]/s/^\([[:space:]]*\)#/\1/;' file_pathhttps://stackoverflow.com/questions/64985830
复制相似问题