Issue
The below example gives the required result but it works for consecutive and non-consecutive pattern search
I need to have this logic only for consecutive patterns
ORANGE should be inserted after every 3 continuous occurrences of APPLE
sed "/APPLE/{p;s/.*/1/;H;g;/^\(\n1\)\{3\}$/s//ORANGES/p;d}" < input.txt > output.txt
Input
APPLE
APPLE
APPLE
APPLE
APPLE
APPLE
APPLE
APPLE
MANGO
APPLE
APPLE
CURRENT OUTPUT
APPLE
APPLE
APPLE
ORANGE
APPLE
APPLE
APPLE
ORANGE
APPLE
APPLE
MANGO
APPLE
ORANGE -------->>> NOT NEEDED <<
APPLE
Solution
This might work for you (GNU sed):
sed '/APPLE/!b;n;//!b;n;//!b;a\ORANGE' file
This will append the line ORANGE
after 3 consecutive lines with the string APPLE
contained with them.
To parametrize the above solution for n consecutive lines (e.g. 5), use:
sed '/APPLE/!b;'$(printf 'n;//!b;%.0s' {2..5})'a\ORANGE' file
Another alternative:
sed '/APPLE/!b;:a;N;/\n[^\n]*APPLE[^\n]*$/!b;s/[^\n]*/&/3;Ta;a\ORANGE' file
If the value to be appended is a variable, use:
sed '/APPLE/!b;:a;N;/\n[^\n]*APPLE[^\n]*$/!b;s/[^\n]*/&/3;Ta;a\'"$var" file
Answered By - potong Answer Checked By - Gilberto Lyons (WPSolving Admin)