Jounathaen
Jounathaen

Reputation: 890

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.

Upvotes: 0

Views: 196

Answers (2)

anubhava
anubhava

Reputation: 785146

Using tac with awk:

tac file.c | awk '/MARKERFUNCTION/{p=NR} p && NR==p+2{print "new line added"} 1' | tac

void foo () {
  bar();
}

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

Upvotes: 2

Sundeep
Sundeep

Reputation: 23667

$ 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

Upvotes: 3

Related Questions