Sed remove all beginning pattern matches from line

I have the following line:

abababtestab

I’m trying to figure out a sed expression to remove all occurrences of ab from the beginning of the line so the transformed line should be:

testab

I feel like this should be simple, but I really don’t know anything about sed.

What I have so far is:

sed 's/^ab//'

But this only removes the first occurrence of ab.

Asked By: Dan

||
sed 's/^(ab)*//' <in >out

You should group it.

echo ababababtestab |
sed 's/^(ab)*//'

testab

Some older seds may not handle that very well, though. Though sub-expression duplication is a POSIX-specified feature of BRE, some seds don’t properly support it. In some of those, though…

echo abababtestab |
sed 's/^(ab)1*//'

…might work instead.

Answered By: mikeserv

Another sed:

sed -e ':1' -e 's/^ab//;t1'

With each line of input, we set up a label :1, then doing substitution ab at start of line. If substitution successfully, test command branch to label 1, redo the work until no ab pattern appeared at the start of line, we’re done.

Answered By: cuonglm

Might be easier to work on the reversed string. That way you can remove all (reversed) ocuurences except the first one.

$ echo "abababtestab" |
rev | sed 's/ba//2g' | rev
testab

This will work even if your string does not start with the pattern.

Answered By: elmo
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.