awk - 在模式匹配后插入一行,如果只有字符串不存在

标签 awk sed grep

输入文件

Ranges:
- PeakK2:8.8.9
- rover-heal:3.3.1
Arg: V1
change: 1
首先,检查文件中是否存在字符串cpu-management,如果不存在,则将其添加到如下所示的rover-heal行之后。
Ranges:
- PeakK2:8.8.9
- rover-heal:3.3.1
- cpu-management:1.9.0
Arg: V1
change: 1
我想出了一个单衬
grep -e "cpu-management:" test.yaml || sed -i -e "/rover-heal/- cpu-management:${version}/"  test.yaml
哪里version是环境变量。
错误:
sed: -e expression #1, char 16: unknown command: `-'

最佳答案

这可以通过 awk 来完成,请尝试以下。您可以将其用作单个代码。

awk -v val="${version}" '
FNR==NR{
  if($0~/cpu-management/){
    found=1
  }
  next
}
/rover/ && found==""{
  print $0 ORS "- cpu-management:" val
  next
}
1
' Input_file  Input_file
根据埃德先生的建议,您也可以使用上面的方法或使用以下方法进行以下操作。
awk -v val="${version}" '
FNR==NR{
  if($0~/cpu-management/){
    found=1
  }
  next
}
{
  print
}
/rover/ && !found{
  print "- cpu-management:" val
}
' Input_file  Input_file
对于您显示的示例,输出将如下所示:
Ranges:
- PeakK2:8.8.9
- rover-heal:3.3.1
- cpu-management:1.9.0
Arg: V1
change: 1
说明:为上述添加详细说明。
awk -v val="${version}"         ##Starting awk program from here.
FNR==NR{                        ##Checking condition FNR==NR which will be treu when 1st time Input_file is being read.
  if($0~/cpu-management/){      ##Checking condition if line contains cpu-management then do following.
    found=1                     ##Setting found to 1 here.
  }
  next                          ##next will skip all further statements from here.
}
/rover/ && found==""{           ##Checking if line has rover AND found is NULL then do following.
  print $0 ORS "- cpu-management:" val ##Printing current line ORS with new value.
  next                          ##next will skip all further statements from here.
}
1                               ##Printing current line here.
' Input_file  Input_file        ##Mentioning Input_file name here.

关于awk - 在模式匹配后插入一行,如果只有字符串不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67020790/

相关文章:

regex - AWK Regex 查找特定模式

Bash 脚本使用 awk 或 sed 将文件中的特定行移动到其他行?

regex - 使用多行正则表达式获取 grep 上下文

sed - 按特定行范围内的模式删除行

bash - 将 csv 文件拆分成多个部分,复制标题

grep - GNU makefile 中的 $(shell) 函数导致 'unterminated call to function shell: missing )'

shell - 使用 sed 注释掉 .env 条目

regex - 如何删除文件开头的以 "//"开头的行(例如文件头)?

linux - 在 awk 中删除\r\n

linux - 如何创建由单独的输入行初始化的系统变量