Kay Chan
Kay Chan

Reputation: 303

Removing pattern at the end of a string using sed or other bash tools

I would like to remove any ABC at the end of the string.

The best I have came up with is

echo ${String}| sed -e 's/["ABC"]*$//g'

However, it will remove all the A, or B or C at the end of the string.

If String is DAAAAABCBBBCCABCABC, if I use the above expression, it will return "D", instead of "DAAAAABCBBBCC"

Is there any better way of doing this? Thanks.

Upvotes: 30

Views: 87520

Answers (3)

mabraham
mabraham

Reputation: 3016

bash can do this internally. The following removes any "ABC" string at the end, and its result can used in variable assignment, a command or whatever:

${String%ABC}

You can also use a regex, not just a simple string match. See http://tldp.org/LDP/abs/html/string-manipulation.html

Upvotes: 34

anubhava
anubhava

Reputation: 786291

You should use:

sed -E 's/(ABC)+$//'

OR:

sed -r 's/(ABC)+$//'

Both will give output:

DAAAAABCBBBCC

Upvotes: 6

Birei
Birei

Reputation: 36282

This should work:

echo "DAAAAABCBBBCCABCABC" | sed -e 's/\(ABC\)*$//g'

Result:

DAAAAABCBBBCC

Surround string between parentheses and * applies to all letters inside them in that exact order.

Upvotes: 30

Related Questions