【问题标题】:using bash with sed how to extract ip from a hostname command and saving it in /etc/hosts file使用 bash 和 sed 如何从主机名命令中提取 ip 并将其保存在 /etc/hosts 文件中
【发布时间】:2020-08-04 07:26:33
【问题描述】:

我想在 /etc/hosts 文件中为我所在的机器的 IP 存储一个条目。

当我运行以下命令时,我得到:

:-$ hostname
ip-10-55-9-102

我想将此条目存储在 /etc/hosts 中,如下所示:

预期结果:10.55.9.102 ip-10-55-9-102

我试过了,但到目前为止......

当前解决方案:

ip=$(hostname -I | cut -d ' ' -f1); echo "$ip ip-${ip//+([.:])/-}" >> /etc/hosts

实际结果:10.55.9.102 ip-10.55.9.102

注意:预期有“-”,实际有“。”数字之间。

【问题讨论】:

  • @Aserre 第二部分....一个有“-”,另一个有“.”

标签: bash sed hostname hosts-file


【解决方案1】:

您的逻辑很好,但您在字符串替换中没有使用正确的模式。你应该写下以下内容:

ip=$(hostname -I | cut -d ' ' -f1); echo "$ip ip-${ip//[.:]/-}" >> /etc/hosts

【讨论】:

    【解决方案2】:

    使用 awk 怎么样?

    hostname | awk -F- '{printf "%s.%s.%s.%s %s\n", $2, $3, $4, $5, $0}' >> /etc/hosts
    

    awk 命令使用-F- 标志将破折号指定为字段分隔符。 printf 命令挑选出字段#2、3、4、5,以及整行的$0。

    【讨论】:

      【解决方案3】:

      用普通的bash:

      ip=$(hostname -I)
      ip=${ip%%[[:space:]]*}
      printf "%s\tip-%s\n" "$ip" "${ip//./-}" # >> /etc/hosts
      

      如果 # 按预期工作,请删除它。

      【讨论】:

        【解决方案4】:

        有一个系统变量$HOSTNAMEhostname 命令相同。因此,如果您的主机名包含 IP 地址,您可以这样做:

        ip=${HOSTNAME//ip-} # create 'ip' var from $HOSTNAME and remove 'ip-'
        ip=${ip//-/.}       # change '-' to '.' in 'ip' var
        printf "$ip\t$HOSTNAME" >> /etc/hosts # add desired string to /etc/hosts
        

        或者使用hostname获取ip:

        ip=( $(hostname -I) )
        printf "$ip\t$HOSTNAME" >> /etc/hosts
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-10-06
          • 1970-01-01
          • 2011-07-05
          • 2020-07-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多