输入文件
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/