如何将一个文件的选定内容插入到另一个文件的模式后面?

如何将一个文件的选定内容插入到另一个文件的模式后面?

我想从 file1 中提取 [abc] 下的 IP,并用它们替换文件 2 中的主机列表:

文件1:

[abc]
192.168.29.153
192.168.29.155
[def]
192.168.29.153
[xyz]
192.168.29.153

文件2:

output.logstash:
  # The Logstash hosts
  hosts: ["192.168.29.115:5044"]

  # Optional SSL. By default is off.
  # List of root certificates for HTTPS server verifications
  #ssl.certificate_authorities: ["/etc/pki/root/ca.pem"]

  # Certificate for SSL client authentication
  #ssl.certificate: "/etc/pki/client/cert.pem"

答案1

我想这样就可以了,如果awk可以的话。

#! /usr/bin/awk -f

# here, NR is record number, and FNR is *file* record number - this matches only 
# in first file
NR == FNR {
    # if first field matches
    if ($1 ~ /abc/) {
        # arrange addresses with `", "` between them
        abc=$2
        for (i=3; i<=NF; i++) abc = abc "\", \"" $i
    } 
    # then we're finished with this file.
    next;
}

$1 ~ /hosts/ {
    # print the saved addresses formatted with `["` addr `"]`
    printf "  %s [\"%s\"]\n", $1, abc ;
    next
 }

# print any other lines with no editing.
{ print }

提供更新文件的输出,如下所示。请注意,内置变量 RS(记录分隔符)正在文件之间更新,以单独处理每个文件。

~$ ./log_edit RS='[' hosts RS='\n' logstash
output.logstash:
  # The Logstash hosts
   hosts: ["192.168.29.153", "192.168.29.155"]

  # Optional SSL. By default is off.
  # List of root certificates for HTTPS server verifications
  #ssl.certificate_authorities: ["/etc/pki/root/ca.pem"]

  # Certificate for SSL client authentication
  #ssl.certificate: "/etc/pki/client/cert.pem

您还需要保存输出然后替换旧文件。

相关内容