キー:値でファイルをフォーマットするのに役立ちます。 [重複]

キー:値でファイルをフォーマットするのに役立ちます。 [重複]

次の値を持つファイルがあります。

猫データ.txt

server1: 'calv'
server2: 'anot'
log: '/u/log/1'
server3: 'calv'
server4: 'anot'
server5: 'secd'
server6: 'calv'
LIB_TRGT_calv,anot: '/tmp/hello.txt'
LIB_TRGT_secd: '/var/del.tmp'

_TRGT_LIB_TRGT_calv,anotつまり、&を含む変数を取得します。LIB_TRGT_secd

注:変数名は異なる場合があります。DB_TRGT_<whatever>

_TRGT_calv,anotieと上記の変数の後に名前を取得する必要がありますsecd

次に、&& を含むすべての項目をインポートcalv & anot & secdし、次のように見つかった項目を data.txt に追加する必要があります。calvanotsecd

希望の出力:

server1: 'calv'
server2: 'anot'
log: '/u/log/1'
server3: 'calv'
server4: 'anot'
server5: 'secd'
server6: 'calv'
LIB_TRGT_calv,anot: '/tmp/hello.txt'
LIB_TRGT_secd: '/var/del.tmp'
LIB_server1:  '/tmp/hello.txt'
LIB_server2:  '/tmp/hello.txt'
LIB_server3:  '/tmp/hello.txt'
LIB_server4:  '/tmp/hello.txt'
LIB_server6:  '/tmp/hello.txt'
LIB_server5: '/var/del.tmp'

これまで私がしたことは次のとおりです。

grep TRGT* data.txt | cut -d: -f1 |cut -d_ -f3
calv,anot
secd

もっと遠く

grep TRGT* test.txt | cut -d: -f1 |cut -d_ -f3 | sed -n 1'p' | tr ',' '\n'
calv
anot

xargsどうやって使い続けるのかわかりません。

ベストアンサー1

これはYAMLなので、YAMLパーサーを使用してくださいyqhttps://kislyuk.github.io/yq/

与えられた入力データfileと短いスクリプトscript

$ yq -y -f script file
server1: calv
server2: anot
log: /u/log/1
server3: calv
server4: anot
server5: secd
server6: calv
LIB_TRGT_calv,anot: /tmp/hello.txt
LIB_TRGT_secd: /var/del.tmp
LIB_server1: /tmp/hello.txt
LIB_server2: /tmp/hello.txt
LIB_server3: /tmp/hello.txt
LIB_server4: /tmp/hello.txt
LIB_server5: /var/del.tmp
LIB_server6: /tmp/hello.txt

これは、jq次のスクリプト(yqJSONパーサーの周りのYAMLラッパーjq)を使用して実行されます。

with_entries(
        select(.key | test("_TRGT_")) |
        .value as $v |
        .key | sub(".*_TRGT_"; "") | split(",")[] |
        { key: ., value: $v }
) as $map |
. += with_entries(
        select(.value | in($map)) |
        { key: ("LIB_" + .key), value: $map[.value] }
)

$mapまず、質問のデータに基づいて、_TRGT_元のデータのキーから解析されたパス名と特殊キー値の間の単純なマッピングになるJSONオブジェクトを計算します。

{                         
  "calv": "/tmp/hello.txt",
  "anot": "/tmp/hello.txt",
  "secd": "/var/del.tmp"
}                          

このオブジェクト$mapのキーに対応する元のデータの各値について、値のキーから計算されたキーとそのアイテムから取得された値を使用して新しいアイテムが生成されます$map

おすすめ記事