How to remove space between distinct chars in a string using sed?
I want开发者_StackOverflow社区 to remove the space between two distinct chars separated by space.
For example
In String "hello world doddy", I want the space between hello & world be removed (but preserve the space between world and doddy, since d d pattern needs to be preserved).
I tried:
$ echo "hello world doddy" | sed 's/\(.\) \([^\1]\)/\1\2/g'
But ended up with
helloworlddoddy
Prep the string by first doubling any space that is between two identical characters. The intervening space shifts from being between two identical characters to between one of the characters and a space, so all spaces can be checked the same way.
echo "hello world doddy" | sed -e 's/\(.\) \1/\1 \1/g' -e 's/\(.\) \(.\)/\1\2/g'
You cannot use a backref inside a character class.
I would approach this by using a sentinel for those cases where the space should be preserved, like so:
echo "hello world doddy" |
sed 's/\([^ ]\) \1/\1<<>>\1/g;s/\([^ ]\) \([^ ]\)/\1\2/g;s/<<>>/ /g'
Edit: changed .
to [^ ]
to avoid manging double spaces, just to be more precise. Thanks for the suggestion.
精彩评论