Saket Kumar
Saket Kumar

Reputation: 13

Replacing space with underscore at specific positions only, using sed

I have some CREATE statement like

CREATE TABLE [a b]{ }
CREATE TABLE [anything everything]{}

Now I want to replace the space within the brackets with _, i.e. the output should be:

CREATE TABLE [a_b]{ }
CREATE TABLE [anything_everything]{ }

I tried using sed, but I am not able to preserve the strings.

Upvotes: 0

Views: 80

Answers (1)

F. Hauri  - Give Up GitHub
F. Hauri - Give Up GitHub

Reputation: 71017

Minimal sed:

sed 's/\(\[[^] ]*\) /\1_/'

If you may find more than one space between brackets:

sed ':a;s/\(\[[^] ]*\) /\1_/;ta'

And as commented by glenn jackman, for BSD version of sed, semicolon don't work as expected. But you could write something like:

sed -e ':a' -e 's/\(\[[^] ]*\) /\1_/' -e 'ta'

But I repeat: you have to use this branch loop only if you expect to find more than one space (one replacement) between brackets ( Create table [more than one space] { ).

Upvotes: 3

Related Questions