This might work for you (GNU sed):
sed -e '/B/!b;x;s/^/x/;/^x\{1\}$/{x;aE' -e 'b};x' file
sed -e '/B/!b;x;s/^/x/;/^x\{2\}$/{x;n;N;d};x' file
Both these solutions can be split into three parts:
- Focus on a particuar regexp
- Counting
- Conditional on the above
If the regexp is not true, continue as normal
If the regexp is true, count it by appending a character (x
) to the hold space for each occurrence.
Condtional on the count (in the first solution, 1 and the second solution, 2) carry out an action.
In the first solution:
- append a line containing
E
In the second solution:
- print the current line
- append the next two lines
- delete the current pattern space
If the conditional is not true, continue as normal.
N.B. the first solution can be shortened using ranges:
sed '0,/B/!b;//aE' file
or for variations of sed that do not allow GNU extentions (0,address
)
sed -e '/B/{aE' -e ':a;n;ba}' file