BDR BDR - 1 year ago 67
Perl Question

SED / PERL : Replace spaces outside or inside single quotes

I have input which has some fields

  • separated by spaces,

  • some other are enclosed in quotes and also seperated by spaces

Here is an example
active=1 'oldest active'=0s disabled=0 'function call'=0

I would like to replace :

  • all spaces outside quotes by

  • all inside quotes by

In order to have
. I tried different solutions with
found on the web but did not managed to do want I want.

Can someone help me ?
Thanks in advance.

Answer Source
$ echo "active=1 'oldest active'=0s disabled=0 'function call'=0" | perl -pe "s/'[^']*'(*SKIP)(*F)| /|/g; s/ /_/g"

Two step replacement:

  • First, '[^']*'(*SKIP)(*F) will skip all patterns surrounded by ' and replace the remaining spaces with |
  • Second, the spaces now left inside ' will be replaced with _
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download