I want to use sed to change the following text:




Can each group between the parenthesis separators be captured and then reconstructed in order with period separators assuming that there will be from 2 to n+3 groups (infinity)? Is there another way?

I am already familiar with:


but that only yields:

  • For the purposes of the RE is the number in brackets relevant? – roaima Mar 15 '16 at 19:53
  • 1
    Nothing stopping you from removing the first and last dot. – don_crissti Mar 15 '16 at 20:03

This appears to satisfy your requirement. I'm not entirely sure whether you are looking to use the numbers in the brackets to validate the run-lengths, but I'm assuming not.

echo '(3)www(5)first(3)nth(6)domain(3)com(0)' |
sed -r -e 's/^\([0-9]+\)//' -e 's/(.)\([0-9]+\)(.)/\1.\2/g' -e 's/\([0-9]+\)$//'

The sed uses three different REs. The first and last strip off the bounded leading and trailing (\d+) expressions. The middle one strips the remainder.

  • basically three passes of sed? Is there no way to do it in just one pass? There is a reason for needing just one pass (sedcmd). – landen99 Mar 15 '16 at 20:29
  • 1
    @landen99 one pass with three operations. Try it. – roaima Mar 15 '16 at 21:51

How about s/\([0-9]+\)/./g; s/^\.|\.$//g?

Your \d construction won't be recognized by some sed implementations. The above is a Posix extended regular expression. Which, you know, should work.

The trick in sed is just to work incrementally. You got most of the way there by replacing the parenthesized digits; you just didn't realize you could clean up the result with a second regex.

  • The thing is that extended regex is not (yet) supported by POSIX sed. You'll have to use BRE for full portability. – don_crissti Mar 15 '16 at 20:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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