【问题标题】:Replace everyting after every time different string每次不同的字符串后替换所有内容
【发布时间】:2014-09-28 04:28:20
【问题描述】:

想要使用第二个 grep 的结果 ip 更改 security.server.ip=* 之后的所有内容。

第一个 Grep:

cat admin.conf|grep security.server.ip|grep -v ^#

结果:

security.server.ip=10.10.1.2

第二次grep:

cat /etc/hosts|grep -i admin-server|head -1|awk '{ print $1}

结果:

10.10.1.2

有时 security.server.ip 在 admin.conf 上会有所不同,我想知道如何用一个命令替换它,该命令将从第二个 grep 中捕获 IP 地址并将其替换为第一个。

【问题讨论】:

  • sed: Replace part of a line 的可能副本。只需将值存储在变量中,然后在该问题中使用答案。
  • 全部使用 awk,开头的 cat 也完全没有意义,因为命令将文件作为参数
  • 我不知道该怎么做,即使下面的例子也不起作用!
  • 把你的问题写得更连贯,你会得到更好的答案,给出预期的输出,并试着更好地解释你真正想要的,因为它不是很清楚。

标签: perl awk sed grep


【解决方案1】:

您可以使用脚本:

#!/bin/sh
IP=$(exec grep -i admin-server /etc/hosts | awk '{ print $1; exit }')
sed -i "/^security\.server\.ip=/s|=.*|=$IP|" admin.conf

【讨论】:

  • sed 中是否可以包含 IP 变量,是否有允许执行 bash 命令的选项?
  • sed 中要包含的 IP 变量是什么意思?我的脚本不是已经这样做了吗?
  • 那个脚本没有按预期工作我收到一些错误:sed: -e expression #1, char 45: unterminated `s' command
  • @KalinBorisov 对不起。我现在添加了终止分隔符。
【解决方案2】:

你可以把它保存在一个变量中:

NEWIP=`grep -i admin-server /etc/hosts|head -1|awk '{ print $1}'` \
sed -i "s/^security\.server\.ip=[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/security\.server\.ip=$NEWIP/" admin.conf

【讨论】:

    【解决方案3】:

    使用 GNU awk 进行就地编辑、nextfile 和 gensub():

    gawk -i inplace '
        NR==FNR{ if (tolower($0) ~ /admin-server/) { ip=$1; nextfile } next }
        { $0=gensub(/(security\.server\.ip=).*/,"\\1"ip,""); print }
    ' /etc/hosts admin.conf
    

    【讨论】:

      猜你喜欢
      • 2020-05-02
      • 2020-12-17
      • 1970-01-01
      • 2021-06-08
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多