sed or awk add content to a body of a c function running in git bash v2.21.0

Viewed 43

To turn this function in a c file (test.c)

void Fuction(uint8, var)
{
  dosomething();
}
// void Fuction(uint8, var)
// should not be injected below a comment with same pattern content

into:

void Fuction(uint8, var)
{
  injected1();
  injected2();
  injected3();
  dosomething();
}
// void Fuction(uint8, var)
// should not be injected below a comment with same pattern content

By injecting this one (inject.c)

injected1();
injected2();
injected3();

I tried several approaches with sed and awk but actually i was not able to inject the code below the open curly braces the code was injected before the curly braces.

On a regex website I was able to select the pattern including the curly braces, but in my script it did not work. May be awk is more compatible, but I have no deeper experiance with awk may some one coeld help here?

With awk i had a additional problem to pass the pattern variable with an ^ancor

call in git bash should be like this:

./inject.sh "void Fuction(uint8, var)" test.c inject.c

(my actual inject.sh bash script)

PATTERN=$1
FILE=$2
INJECTFILE=$3

sed -i "/^$PATTERN/r $INJECTFILE" $FILE
#sed -i "/^$PATTERN\r\{/r $INJECTFILE" $FILE

I actually have no idear to catch also the \n and the { in the next line My result is:

void Fuction(uint8, var)
injected1();
injected2();
injected3();
{
  dosomething();
}
// void Fuction(uint8, var)
// should not be injected below a comment with same pattern content
1 Answers

Expanding on OP's sed code:

sed "/^${PATTERN}/,/{/ {
/{/ r ${INJECTFILE}
}" $FILE

# or as a one-liner

sed -e "/^${PATTERN}/,/{/ {" -e "/{/ r ${INJECTFILE}" -e "}" $FILE

Where:

  • /^${PATTERN}/,/{/ finds range of rows starting with ^${PATTERN} and ending with a line that contains a {
  • { ... } within that range ...
  • /{/ r ${INJECTFILE} - find the line containing a { and append the contents of ${INJECTFILE}

Results:

$ ./inject.sh "void Fuction(uint8, var)" test.c inject.c
void Fuction(uint8, var)
{
injected1();
injected2();
injected3();
  dosomething();
}
// void Fuction(uint8, var)
// should not be injected below a comment with same pattern content

Once OP verifies the output the -i flag can be added to force sed to overwrite the file.

NOTE: OP's expected output shows the injected lines with some additional leading white space; if the intention is to auto-indent the injected lines to match with the current lines ... I'd probably want to look at something like awk in order to provide the additional formatting.

Related