linux - 注释和取消注释以空格开头的特定行

标签 linux shell ubuntu

我刚开始使用 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
但是,虽然这适用于每个 block 的第 1 行,但它不适用于第 3 行,其中 # 符号前有空格,我不知道如何更改

最佳答案

这可以通过在示例“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
第三个命令遵循与第二个相同的逻辑,但这次不保留任何空格

关于linux - 注释和取消注释以空格开头的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64985830/

相关文章:

ubuntu - 如何从 Ubuntu/*nux 中完全删除 VTK?

.htaccess - 除了特定 URL 之外的所有页面上的 nginx 基本身份验证,它遵循

linux - 遍历 bash 命令

xml - 使用 xmllint 从 xml 中获取多次出现的属性值

c++ - 制作图形用户界面编辑器

bash - 如何将base64编码的内容传递给sed?

linux - 杀死旧进程后启动新进程(如果存在)

bash - 检测/避免多次 apt-get/dpkg 安装

android - 未应用 Udev 规则

linux - 如何在Ubuntu中卸载库(通过编译安装)?