I have a markdown file with sections separated by headings. I want to perform a search and replace only on specific sections; however, each section has similar content, so a global search and replace would end up affecting all sections. Because of this, I would need to somehow limit the search and replace to only certain sections of the file.
For example, say I wanted to replace all instances of foo with bar under # Section 1, # Section 3, and # Section 4 leaving # Section 2 and # Section 5 unchanged, as shown below
Sample Input:
# Section 1
- foo
- foo
- Unimportant Item
- foo
- Unimportant Item
# Section 2
- foo
- Unimportant Item
# Section 3
- foo
- Unimportant Item
# Section 4
- foo
- Unimportant Item
- foo
# Section 5
- foo
- foo
Sample Output
# Section 1
- bar
- bar
- Unimportant Item
- bar
- Unimportant Item
# Section 2
- foo
- Unimportant Item
# Section 3
- bar
- Unimportant Item
# Section 4
- bar
- Unimportant Item
- bar
# Section 5
- foo
- foo
If I didn't have to worry about the individual sections, a global search and replace would be trivial by using
sed -i 's/foo/bar/g' <input_file>
but I'm not sure if sed is capable of checking context to allow what I am looking for.