【问题标题】:Ubuntu SED: Replacing with regular expressionsUbuntu SED:用正则表达式替换
【发布时间】:2013-08-25 08:33:45
【问题描述】:

我想替换输入文件中的文本。输入文件包含以下输入文本:

...
[
%% 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
...

我尝试输入以下 SED 正则表达式:

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

因此,我希望将旧 IP 地址 192.168.58.999 替换为服务器的实际 IP 地址。 “my_ip”变量与前一步的服务器 IP 值一起归档。 SED 执行正则表达式并返回没有错误,但也没有对文件进行任何更改。

我将不胜感激有关此问题的任何帮助。 (我使用的是 Ubuntu 12.04.2,64 位)

【问题讨论】:

  • 如果我们能看到输入可能会更容易。如果它很长,只需几行。
  • 嗯,您在第一个 d 之前缺少一个反斜杠...这有帮助吗?
  • 如果您想replace a text from an input file,请告诉我们a text from an input file,以便我们为您提供帮助。
  • 大家好,你们是完全正确的。这是输入文件中的更多行。反斜杠已经在正则表达式中。我现在在本文中更正了它。

标签: regex replace sed


【解决方案1】:

这有帮助吗?

kent$ my_ip="newIpAddr"

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

【讨论】:

    【解决方案2】:

    第一个 \d 缺少反斜杠,但这没有实际意义,因为 sed 无论如何都不理解 \d

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

    变化:

    • 添加了-r 标志以启用扩展正则表达式。花括号需要。
    • 使用[0-9] 而不是\d
    • \. 转义.,使其匹配句点而不是任何字符
    • \.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3} 缩短为 (\.[0-9]{1,3}){3}

    【讨论】:

    • 您好约翰,谢谢您的回答。无论如何,它没有帮助。我还缺少其他东西吗?
    【解决方案3】:

    好的,

    我设法解决了这个问题。使用以下 SED 代码 sn-p 它对我有用。

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

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 2018-08-22
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多