Ankur
Ankur

Reputation: 13

How to insert a keyword after 3 CONSECUTIVE pattern using SED

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

Upvotes: 1

Views: 66

Answers (2)

potong
potong

Reputation: 58438

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

Upvotes: 0

KamilCuk
KamilCuk

Reputation: 141235

ORANGE should be inserted after every 3 continuous occurrences of APPLE

The following script:

#!/bin/bash

cat <<EOF |
APPLE
APPLE
APPLE
APPLE
APPLE
APPLE
APPLE
APPLE
MANGO
APPLE
APPLE
APPLE
EOF
sed '
# Add to hold space and inspect hold space
H
x
/^\(\nAPPLE\)\{3\}$/{
    # 3 apples in hold space, means we add orange to pattern space
    # and clear hold space
    s///
    x
    s/$/\nORANGE/
    x   
}
# There are at least 3 lines in hold space
/^\(\n[^\n]*\)\{3\}/{
    # Remove first line from hold space
    s/\n[^\n]*//
}
x
'

outputs:

APPLE
APPLE
APPLE
ORANGE
APPLE
APPLE
APPLE
ORANGE
APPLE
APPLE
MANGO
APPLE
APPLE
APPLE
ORANGE

Upvotes: 1

Related Questions