Operating System - HP-UX
1753259 Members
5158 Online
108792 Solutions
New Discussion

Re: String manipulation: How to replace all n consecutive "_" characters by only one &quot

 
SOLVED
Go to solution
SwissKnife
Frequent Advisor

String manipulation: How to replace all n consecutive "_" characters by only one "_" ?

Hi All,

Here is a list of strings.

CONFOTA______ora___________________________________.aud
CONFOTA_____cjq_________.trc
CONFOTA__dbrm_________.trc
CONFOTA___lgwr_________.trc

How to replace all n consecutive "_" characters by only one "_" to obtain the result as below ?:

CONFOTA_ora_.aud
CONFOTA_cjq_.trc
CONFOTA_dbrm_.trc
CONFOTA_lgwr_.trc

 

Thanks in advance for your apprciated help,

Kind regards,

Den.

2 REPLIES 2
Steven Schweda
Honored Contributor
Solution

Re: String manipulation: How to replace all n consecutive "_" characters by only one &quot

> How to replace all n consecutive "_" characters by only one "_" to
> obtain the result as below ?:

mba$ echo 'CONFOTA_____cjq_________.trc' | sed -e 's/__*/_/g'
CONFOTA_cjq_.trc

   For one "_" followed by any number (0, 1, 2, ...) of "_" ("_*"),
substitute one "_", and repeat for all non-overlapping matches ("g").

Bill Hassell
Honored Contributor

Re: String manipulation: How to replace all n consecutive "_" characters by only one &quot

Another solution is to use tr like this:

echo 'CONFOTA_____cjq_________.trc' | tr -s '_'

-s option will replace two or more consecutive occurrences of the specified character with a single instance of that character.



Bill Hassell, sysadmin