部分文字列に基づいてデータをマッピングする方法は?

部分文字列に基づいてデータをマッピングする方法は?

以下からデータを取得します。

staging_uw_pc_account_contact_role_hive_tb
staging_uw_pc_account_hive_tb
staging_uw_pc_account_location_hive_tb
uw_pc_account_contact_hive_tb
uw_pc_account_contact_hive_tb_backup
uw_pc_account_contact_role_hive_tb
uw_pc_account_contact_role_hive_tb_backup

次の規則に従って地図を作成するにはどうすればよいですか?

  1. _backup最後から削除
  2. staging_最初から削除
  3. ここでマッピングを確認してください。

結果は次のとおりです。すべてのテーブルにステージングとバックアップがあるわけではなく、この場合、これらのフィールドは空でなければなりません。

uw_pc_account_contact_role_hive_tb, uw_pc_account_contact_role_hive_tb_backup, staging_uw_pc_account_contact_role_hive_tb

ベストアンサー1

次のスクリプトは、各入力行にプレフィックスおよび/またはサフィックスawkの存在を検出します。staging__backup

接頭辞と接尾辞がある場合は削除され、残りの文字列は連想配列のキーとして使用されますmap

元の行は、map生成されたキーに関連付けられたカンマ区切り文字列として配列に格納されます。

最後に、map内容全体を印刷してみてください。

BEGIN {
        OFS = ", "
        prefix = "staging_"
        suffix = "_backup"
}

{
        key = $0
        sub("^" prefix, "", key)
        sub(suffix "$", "", key)

        map[key] = (map[key] == "" ? $0 : map[key] OFS $0)
}

END {
        for (key in map) print map[key]
}

ファイルの問題データを使用してテストを実行しますfile

$ awk -f script file
staging_uw_pc_account_location_hive_tb
staging_uw_pc_account_hive_tb
uw_pc_account_contact_hive_tb, uw_pc_account_contact_hive_tb_backup
staging_uw_pc_account_contact_role_hive_tb, uw_pc_account_contact_role_hive_tb, uw_pc_account_contact_role_hive_tb_backup

出力の個々の行のフィールドの順序は、ソースファイルの行の順序によって決まります。

おすすめ記事