Match a pattern within a block of text bounded by two different patterns

Viewed 61

Is there a way to match a pattern within a block of text whose boundaries are two unique patterns on different lines? By that I mean:

/*some comment*/
void something_patternWord1()
{
   some_code;
   some_code;
   some_code_patternWord3;
   some_code;
}
/*some comment patternWord2

Desired Output:

/*some comment*/
void something_patternWord1()
{
   some_code;
   some_code;
   new_line_of_some_code;   //after performing sed command
   some_code_patternWord3;
   some_code;
}
/*some comment patternWord2

What I've tried:

sed '/patternWord1/,/patternWord2/{/patternWord3/i new_line_of_some_code;}' inputFile > outputFile

The above command doesn't seem to be working.

Ultimately, what I'm trying to achieve is using bash script, read in some stuff from .csv file, and if the word read in is someWord then search for a block of text bounded by patternWord1 and patternWord2, match patternWord3 within that block of text and insert some code above it.

I have many .cpp files with many different functions and therefore many combinations of different patternWord1 and patternWord2.

Is what I'm trying to do even possible with sed, and is sed the best tool for something like this?

Perhaps another approach: would it be possible for me to use if-then statements in bash while having the script read in a .cpp file, and then use the sed command to match for patternWord3 and insert a new line of code?

If you could help me out with sed that would be great, but also I'm open to other suggestions as well if it make more sense/it is more efficient. Thank you in advance.

1 Answers

The point here is to tell the insert command where to stop.

You may do it several ways, either placing the inserted string on a new line, or by closing the sed command with the ' where the inserted line should end.

You may use

sed -e '/patternWord1/,/patternWord2/{/patternWord3/i\
   new_line_of_some_code;
}'

Or,

sed -e '/patternWord1/,/patternWord2/{/patternWord3/i \ \ \ new_line_of_some_code;' -e '}' inputFile > outputFile

See the online demo:

s='/*some comment*/
void something_patternWord1()
{
   some_code;
   some_code;
   some_code_patternWord3;
   some_code;
}
/*some comment patternWord2'

sed -e '/patternWord1/,/patternWord2/{/patternWord3/i \ \ \ new_line_of_some_code;' -e '}' <<< "$s"

Output:

/*some comment*/
void something_patternWord1()
{
   some_code;
   some_code;
   new_line_of_some_code;
   some_code_patternWord3;
   some_code;
}
/*some comment patternWord2
Related