Bugra
Bugra

Reputation: 189

Ubuntu SED: Replacing with regular expressions

I want to replace a text from an input file. The input file contains following input text:

...
[
%% Riak Client APIs config
{riak_api, [
        %% pb_backlog is the maximum length to which the queue of pending
        %% connections may grow. If set, it must be an integer >= 0.
        %% By default the value is 5. If you anticipate a huge number of
        %% connections being initialised *simultaneously*, set this number
        %% higher.
        %% {pb_backlog, 64},

        %% pb is a list of IP addresses and TCP ports that the Riak
        %% Protocol Buffers interface will bind.
        {pb, [ {"192.168.75.999", 8087 } ]}
        ]},

%% Riak Core config
...

I tried to enter the following SED regex expression:

sed -i -e "s/\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}\", 8087/$my_ip\", 8087" /path/to/file

As a result I want to have the old IP address 192.168.58.999 replaced with the server's actual IP address. The "my_ip" variable is filed with the server's IP value from a former step. SED executes the regex expression and returns without error, but also without any changes to the file.

I would appreciate any help regarding this issue. (I'm using Ubuntu 12.04.2, 64 bit)

Upvotes: 0

Views: 2112

Answers (3)

Bugra
Bugra

Reputation: 189

Ok,

I managed to solve the problem. With the following SED code snippet it worked for me.

sed -ire "s/[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\"\, 8087/$my_ip \"\, 8087/g"

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 362157

You're missing a backslash for the first \d, but that's moot since sed doesn't understand \d anyways.

sed -ire "s/[0-9]{1,3}(\.[0-9]{1,3}){3}\", 8087/$my_ip\", 8087/" /path/to/file

Changes:

  • Added -r flag to enable extended regexes. Needed for the curly braces.
  • Use [0-9] instead of \d.
  • Escape . with \. so it matches periods rather than any character.
  • \.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3} shortened to (\.[0-9]{1,3}){3}.

Upvotes: 1

Kent
Kent

Reputation: 195269

does this help?

kent$ my_ip="newIpAddr"

kent$ sed "s/\".*\"/\"$my_ip\"/" <<< '{pb, [ {"192.168.58.999", 8087 } ]}'
{pb, [ {"newIpAddr", 8087 } ]}

Upvotes: 1

Related Questions