Wednesday, December 29, 2021

[SOLVED] Insert a line after pattern match, if only the string does not exists

Issue

Input file

Ranges:
- PeakK2:8.8.9
- rover-heal:3.3.1
Arg: V1
change: 1

Firstly, check if the string cpu-management exists in the file, if not add it after the rover-heal line like below.

Ranges:
- PeakK2:8.8.9
- rover-heal:3.3.1
- cpu-management:1.9.0
Arg: V1
change: 1

I came up with a one liner

grep -e "cpu-management:" test.yaml || sed -i -e "/rover-heal/- cpu-management:${version}/"  test.yaml

where version is the environmental variable.

Error:

sed: -e expression #1, char 16: unknown command: `-'

Solution

This could be done with awk, please try following. You can use it as a single code.

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

OR as per Ed sir's suggestion you could do following too use either above OR use following.

awk -v val="${version}" '
FNR==NR{
  if($0~/cpu-management/){
    found=1
  }
  next
}
{
  print
}
/rover/ && !found{
  print "- cpu-management:" val
}
' Input_file  Input_file

For your shown samples output will be as follows:

Ranges:
- PeakK2:8.8.9
- rover-heal:3.3.1
- cpu-management:1.9.0
Arg: V1
change: 1

Explanation: Adding detailed explanation for above.

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.


Answered By - RavinderSingh13