Jounathaen Jounathaen - 1 month ago 6
Bash Question

Insert Text 2 lines above Pattern

I have some C code from a codegenerator and have to insert a line two lines before a specific mark in the code.

Example, generated Code:

file.c


void foo () {
bar();
}

# <- I want a line to be added here!
void example () {
MARKERFUNCTION();
...
}


I do not know the exact position of
MARKERFUNCTION()
but it appears only once in the file and is the first line in
example()
.
example()
is not a fixed name.

A single sed command would be great, but a combination of grep and something else would do too.

Answer
$ sed '/()\s*{/{N; s/.*MARKERFUNCTION/== Text to add ==\n\0/}' file.c 
void foo () {
  bar();
}

== Text to add ==
void example () {
  MARKERFUNCTION();
  ...
}
  • /()\s*{/ match () followed by any spaces and { - to detect line with function.. if there can be content inside (), using /)\s*{/ could work
  • {N; if above condition matches, get next line
  • s/.*MARKERFUNCTION/== Text to add ==\n\0/ perform substitution by checking if the pattern MARKERFUNCTION is there in the two lines we have. Then in replacement section, add the required text, a newline and the pattern matched which by default is in \0


awk solution, assuming there is a blank line prior to start of function having the required pattern

$ awk -v RS= -v ORS="\n\n" '/MARKERFUNCTION/{$0 = "--Text to add--\n" $0} 1' file.c
void foo () {
  bar();
}

--Text to add--
void example () {
  MARKERFUNCTION();
  ...
}

This reads the input file paragraph wise and if a paragraph contains the required pattern, add a line before printing

Comments