次の値を持つファイルがあります。
猫データ.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,anot
ieと上記の変数の後に名前を取得する必要がありますsecd
。
次に、&& を含むすべての項目をインポートcalv & anot & secd
し、次のように見つかった項目を data.txt に追加する必要があります。calv
anot
secd
希望の出力:
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パーサーを使用してくださいyq
。https://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
次のスクリプト(yq
JSONパーサーの周りの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
。