0

I have a string like

AAA: BBB: CCC: DDD: EEE

and I need to replace

AAA: BBB: CCC:

with

FFF:

so it would look like

FFF: DDD: EEE

Thanks.

3
  • You meant "up to 3rd occurrence" Dec 2, 2019 at 13:50
  • What's wrong with s/AAA: BBB: CCC:/FFF:/?
    – choroba
    Dec 2, 2019 at 13:56
  • @RomanPerekhrest Right. Corrected. Dec 2, 2019 at 14:41

2 Answers 2

1

Using GNU sed and extended regular expressions (-r), the following should work:

sed -r "s/^([^:]*:){3}/FFF:/"

either as in sed <...> filename.txt or echo "$original_string" | sed <...>

This will replace a substring that, starting with the beginning of the line (^), contains three times in a row a pattern consisting of "anything but the colon ([^:])" followed by a colon, with the pattern FFF:.

2
  • Nice! That's exactly what I was looking for. Thanks. Dec 2, 2019 at 14:35
  • 1
    Also works on the MacOSX BSD sed, except change -r to -E (which also works with GNU sed) -- think of -E as enabling extended regular expressions in the same way that grep -E does. Dec 2, 2019 at 16:52
0

You cud use this:

$ sed -e 's/:/\n/3;s/.*\n/FFF:/' file

Here we are making use of the feature found in sed to effect the n-th change , n<=512. Also, the newline is guaranteed to not be seen in a pattern space, unless it has been brought in apriori, by means of the G, H, N, or a literal newline is added, like in our case.

This is gnu sed-ism. We use the escaped literal newline for Posix sed.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .