How to? remove adjacent common chars

  • This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

samintz

Scott Mintz
May 20, 2008
1,203
11
Solon, OH, USA
#1
Is there a simple way to compress a string by reducing the common adjacent characters to a single character? For example a path string with multiple ;;;; reduced to a single ;.

Or multiple spaces reduced to a single space.

SIMPLE being the operative word here.

-Scott
 
Jan 19, 2011
559
7
Norman, OK
#2
Regex replace
Code:
(.){2,}
with
Code:
\1
Edit: OK. That didn't work as great in practice as it sounded in my head. I'm still working on it.
Edit: Here's an updated search string.
Code:
(.)\1+
Edit: Here's an example using sed
Code:
set | sed -r -e "s/(.)\1+/\1/g"
Edit: Make sure to replace the "(.)" with something like "([; ])" or whatever characters you're actually wanting to replace or you'll end up taking out other characters that you want to keep.