ファイルにはコマンドのリストが含まれており、各コマンドには変数の文字列で置き換える必要がある文字列があります。

ファイルにはコマンドのリストが含まれており、各コマンドには変数の文字列で置き換える必要がある文字列があります。

私のスクリプトに2つのファイルをパラメータとして渡したいです。

ファイル 1.txt には以下が含まれます。

host1
host2
host3

ファイル2.txtには次のものが含まれます。

command1 host_name morestuff
command2 host_name mnorestuff

File1から各項目を抽出し、各項目をFile2の一致する "host_name"に置き換えて出力を取得するにはどうすればよいですか?

command1 host1 morestuff
command2 host1 mnorestuff
command1 host2 morestuff
command2 host2 morestuff
command2 host3 morestuff
command2 host3 morestuff

ベストアンサー1

awk両方のファイルを順番に読み書きするスクリプトを作成します。

awk 'FNR == NR { cmd[++n] = $0; next }
    {
        for (i = 1; i <= n; ++i) {
            command = cmd[i]
            sub("host_name", $0, command)
            print command
         } 
    }' File2.txt File1.txt

これにより、コマンドはFile2.txt名前付き配列に読み込まれますcmdFile1.txtを読み取ると、host_name各コマンドの文字列はファイルから読み取られたホスト名に置き換えられ、変更されたコマンドが印刷されます。

質問のデータを考慮すると、結果は次のようになります。

command1 host1 morestuff
command2 host1 mnorestuff
command1 host2 morestuff
command2 host2 mnorestuff
command1 host3 morestuff
command2 host3 mnorestuff

おすすめ記事