別のファイルのパターンの後に1つのファイルの選択を挿入するには?

別のファイルのパターンの後に1つのファイルの選択を挿入するには?

file1から[abc]の下のIPを抽出し、file2のホストのリストをそのIPに置き換えたいと思います。

ファイル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 }

以下のように更新されたファイルの出力を提供します。各ファイルを個別に処理するために、組み込み変数Record Separator(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

また、出力を保存してから古いファイルを置き換える必要があります。

おすすめ記事