Lolly
Lolly

Reputation: 36372

Unix sed command to find and replace a pattern

I am trying to match the below pattern which has spaces in between.

         -DsomeArg=some value 

and to replace it with below pattern using sed command.

         -DsomeArg="some value"

There can be any number of spaces in between. I tried below command but it's not working.

          sed 's/^\(-D.*\)=(.\+\s\+.\+)/\1="\2"/' test.dat

where as .* works instead of .+ , but I want to match one or more pattern. I am not able to find what I am doing wrong.

Upvotes: 1

Views: 13603

Answers (2)

Rob Davis
Rob Davis

Reputation: 15772

This does what you asked for:

sed 's/=\(.*\)/="\1"/'

or a little shorter:

sed 's/=/="/;s/$/"/'

But I have a feeling there's more to the story than you're saying. Like, are you expecting some text to follow "some value" that you want to leave outside of the quotation marks? Does something precede -DsomeArg that you don't want to match?

With regular expressions, context is everything.

Upvotes: 0

Adam Sznajder
Adam Sznajder

Reputation: 9206

cat /tmp/test | sed -r 's/^(-D.*?)=(.+\s+.+)/\1="\2"/'
-DsomeArg="some value"

Hope that will help :)

Upvotes: 1

Related Questions