4

If the string is of the pattern XxxXyzAbc...
The expected out put from sed has to be Xxx Xyz Abc ...

eg: if the string is QcfEfQfs, then the expected output is Qcf Ef Efs.

If i try to substitute the pattern [a-z][A-Z] with space then the sed will replace the character or pattern with space, like Qc f fs.

Is there any way to insert space in between without replacing the pattern ?.

Kindly help. Thanks.

3 Answers 3

6

Use match groups.

$ sed 's/\([a-z]\)\([A-Z]\)/\1 \2/g' <<< 'XxxXyzAbc'
Xxx Xyz Abc
0

A more accurate pattern match - one with fewer spurious matches on strings that are not in the XxxYyyZzz format - is:

sed 's/\([A-Z][a-z][a-z]*\)\([A-Z][a-z][a-z]*\)\([A-Z][a-z][a-z]*\)/\1 \2 \3/'

Consider the inputs:

XxxYyyZzz
xxxYyyZzz
X xY yZ z

One other answer I see will insert spaces in all the strings - when it should only modify the first string.

Updated to allow for the QcfEfEfs example - it isn't clear from the question how many lower case letters in a row are allowed. It could be 1 or 2; or it could be 1 or more - using a * allows for 1 or more; otherwise, use \{1,2\} for 1 or 2.

2
  • You're missing a closing square bracket. Your command fails on the OP's "QcfEfQfs". Dec 22, 2010 at 7:08
  • @Dennis: drat - yup. I fixed it in the version I tested; and forgot to change the code before adding answer. Bother And yes, I missed the QcfEfEfs example...I wonder how many lower-case letters in a row... Dec 22, 2010 at 7:20
0

This might work for you (GNU sed):

sed 's/\B[[:upper:]]/ &/g' file

Looks for a non-word boundary followed by an uppercase character and inserts a space throughout the line.

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.