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

输入文件

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
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

对于您显示的示例,输出将如下所示:

说明:为以上添加详细说明。

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.

  • Really appreciate the explanation.. Found one hiccup though, `${version}` is not getting replaced.
    `- cpu-management:${version}`, where `version` is an env variable.

回答

忽略文件中已经存在的有关 cpu-management 的详细信息(这似乎不是问题的基本方面,并且提供的解决方案已经适用于该问题),sed替换的经典解决方案是使用a

$ sed "/^- rover-heal/a                                         
- cpu-management:${version}
" input-file
Ranges:
- PeakK2:8.8.9
- rover-heal:3.3.1
- cpu-management:
Arg: V1
change: 1

如果您使用的是 bash,则可以使用以下命令简化输入:

$ sed $'/^- rover-heal/an'"- cpu-management:$version"$'n' input-file
Ranges:
- PeakK2:8.8.9
- rover-heal:3.3.1
- cpu-management:
Arg: V1
change: 1

请注意,某些 sed 允许您跳过嵌入的换行符,但并非所有人都这样做。


以上是在模式匹配后插入一行,如果只有字符串不存在的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>