【问题标题】:sed to pick value from one file and replace in anothersed 从一个文件中选择值并在另一个文件中替换
【发布时间】:2019-11-12 23:48:34
【问题描述】:

我正在尝试将一个文件中的值替换为另一个文件:

{ read -r val1
  sed -i 's! nameserver .*; *$! nameserver '$val1';!;' testfile 
} < /etc/resolv.conf

然后替换 nginx 配置中的名称服务器 IP:

server {
  location {
    resolver 1.2.3.4 valid=60s;
    resolver_timeout 10s;
    }

但是我从 sed 收到以下错误: sed: -e expression #1, char 2: unterminateds'命令`

【问题讨论】:

  • testfile 中的示例数据是上面的 nginx 配置。是的,我正在尝试从 /etc/resolv.conf 读取值(IP)并替换解析器之后的任何值(在上面的示例中为 1.2.3.4)
  • @SynRomana 很多程序都可以访问 /etc/resolv.conf;我们需要在您的机器上查看它的结构才能正确回答这个问题。
  • @vintnes 我没有更改 /etc/resolv.conf 中的任何内容我正在从中读取内容,它始终包含包含nameserver 1.2.3.4的行或行

标签: string bash text sed replace


【解决方案1】:

因为我不知道你的 resolv.conf 是如何配置的,所以在黑暗中拍摄:

gawk '
  NR==FNR && $1=="nameserver" {if(ns=$2) nextfile}                    #1
  NR!=FNR && $1=="resolver"   {print gensub(/[^ ]+/, ns, 2); next}    #2
  NR!=FNR                                                             #3
' /etc/resolv.conf testfile > tmp && mv tmp testfile                  #4
  1. 从第一个文件中收集域名服务器
  2. 插入收集的名称服务器,保留前导空格
  3. 打印修改后的第二个文件
  4. 文件更改前测试是否成功

编辑:现在需要 GNU Awk:gensub 动态保留前导空格,nextfile 在我们拥有名称服务器后跳过当前文件

【讨论】:

  • 成功了,但在解析器之前删除了前导空格。
  • @SynRomana 请参阅编辑以获取更简洁但非 POSIX 的解决方案。
猜你喜欢
  • 2020-11-19
  • 1970-01-01
  • 2021-10-04
  • 2018-01-22
  • 2019-03-06
  • 2014-03-15
  • 2016-03-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多