Removing SED spaces inside a string

I am trying to use sed to replace a space inside a string. For example, given the line:

var test = 'Some test text here.';

      

I want to receive:

var test = 'Sometesttexthere.';

      

I tried using ( \x27

matches '

):

sed 's|\x27\([^\x27[:space:]]*\)[[:space:]]|\x27\1|g

      

but that just gives

var test = 'Sometest text here.';

      

Any ideas?

+2


a source to share


2 answers


It's a much more complex sed

script, but it works without a loop. You know, just for the sake of variety:

sed 'h;s/[^\x27]*\x27\(.*\)/\n\x27\1/;s/ //g;x;s/\([^\x27]*\).*/\1/;G;s/\n//g'

      

It creates a copy of the line, splits one (which will become the second half) when the first single camera discards the first half, replaces all spaces in the second half, swaps the copies, splits the other, discards in the second half, concatenates them together and removes the newlines used for splitting, and adds a command G

.

Edit:



To select specific lines to work with, you can use some selection criteria. Here I indicated that the string must contain an equal sign and at least two single quotes:

sed '/.*=.*\x27.*\x27.*/ {h;s/[^\x27]*\x27\(.*\)/\n\x27\1/;s/ //g;x;s/\([^\x27]*\).*/\1/;G;s/\n//g}'

      

You can use any regex that is best suited for inclusion and exclusion for your needs.

+1


a source


There are two problems with your command line:

  • First, it is missing \

    after [^

    .

  • Second, even if you use a modifier g

    , only the first place is removed. What for? As this modifier results in the replacement of consecutive matches in the same line. It will not rescan the entire line from the beginning. But this is required here because your match is being tied to the initial '

    string literal.

The obvious way to solve this problem is to use a loop implemented by a conditional jump (jump from tLabel

to :Label

; t

jumps if at least one s

matches the last test c t

).

This is easiest with a sed script (and you don't need to hide '

), for example:



:a
s|'\([^'[:space:]]*\)[[:space:]]|'\1|
ta

      

But it can be done on the command line. The exact syntax may depend on your taste of sed, for mine (super sed on Windows) it is called like this:

sed -e ":a" -e "s|\x27\([^\x27[:space:]]*\)[[:space:]]|\x27\1|;ta"

      

You need two separate script expressions because the label :a

continues to the end of the expression.

0


a source







All Articles