28

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.

3 Answers 3

32

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

6
  • 1
    This will only remove the last occurrence of ABC. This kind of Shell Parameter Expansion uses glob, so its not possible to express "any number of ABC's" with it. More info: gnu.org/software/bash/manual/… Dec 10, 2012 at 21:39
  • 1
    @LopSae with extended globs (shopt -s extglob), it would work: ${String%%+(ABC)} Jan 17, 2018 at 15:41
  • Is it possible to put regex in there? Nov 9, 2020 at 13:44
  • Yes, see the link. I edited the answer accordingly. Thanks!
    – mabraham
    Nov 9, 2020 at 14:43
  • That's technically not regex btw, but rather a bash glob pattern.
    – tony19
    Jan 18, 2023 at 17:33
29

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.

3
  • Why sed -e 's/\(;;\)*$//g' foo.csv does not delete ;; from end of lines? for example, I have a line County;4;5;0;20;4;5;4;5;; and the output is the same.
    – Sigur
    Sep 13, 2018 at 16:51
  • @Sigur: It works for me. Check that there aren't any blanks at the end.
    – Birei
    Sep 15, 2018 at 18:49
  • 1
    I discovered the problem. It was end of line char. It worked.
    – Sigur
    Sep 17, 2018 at 12:08
6

You should use:

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

OR:

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

Both will give output:

DAAAAABCBBBCC
3
  • 1
    Worth mentioning that both parameters enable interpreting the the expresion as an extended regular expression. I have seen -E used by Mac (Darwin) and -r by other linux distributions. Dec 10, 2012 at 21:37
  • 1
    -E is an undocumented option for compatibility with BSD sed. You should almost certainly be using -r. -E will fail on the busybox version of sed.
    – Six
    Apr 10, 2015 at 2:29
  • 1
    Years of using basic sed and I was confused why sed -e 's/^[0-9]+//' wasn't working. Usually decade old tech answers are outdated but this one wasn't. thanks!
    – Jim
    Jan 31, 2023 at 19:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.