2つのファイルがあり、私がやりたいのはファイルおよび検索番号ファイルb検索された行を含む括弧全体を出力します。それが何と呼ばれているのかはわかりません。
ファイル:
300
302
303
ファイルb:
[300] = {
name = "John",
age = "12",
address = {""},
job = "Marketing",
job a = "some job",
job b = {"some job"},
car = 0,
salary = 0
},
[301] = {
name = "John",
age = "12",
address = {""},
job = "Marketing",
job a = "some job",
job b = {"some job"},
car = 0,
salary = 0
},
[302] = {
name = "John",
age = "12",
address = {""},
job = "Marketing",
job a = "some job",
job b = {"some job"},
car = 0,
salary = 0
},
[303] = {
name = "John",
age = "12",
address = {
"Person street address"
},
job = "Marketing",
job a = "some job",
job b = {
"His job description"
},
car = 0,
salary = 0
},
期待される出力:
[300] = {
name = "John",
age = "12",
address = {""},
job = "Marketing",
job a = "some job",
job b = {"some job"},
car = 0,
salary = 0
},
[302] = {
name = "John",
age = "12",
address = {""},
job = "Marketing",
job a = "some job",
job b = {"some job"},
car = 0,
salary = 0
},
[303] = {
name = "John",
age = "12",
address = {
"Person street address"
},
job = "Marketing",
job a = "some job",
job b = {
"His job description"
},
car = 0,
salary = 0
},
awk を使ってみましたが、動作しません。
awk 'NR==FNR{a[$1]=1;next} $1 in a && /\[$1\]/,/^\t\},/ {print}' a b > c
助けてくれてありがとう..
答え1
この特定の形式のパーサーにアクセスできず、レコードが実際に示されているように単純で規則的であると仮定すると、これはすべての UNIX ボックスの任意のシェルで任意の awk を使用して機能します。
$ cat tst.awk
NR == FNR {
vals["["$1"]"]
next
}
rec == "" { key = $1 }
{ rec = rec $0 ORS }
/^[[:blank:]]*},$/ {
if ( key in vals ) {
printf "%s", rec
}
key = rec = ""
}
。
$ awk -f tst.awk file_a file_b
[300] = {
name = "John",
age = "12",
address = {""},
job = "Marketing",
job a = "some job",
job b = {"some job"},
car = 0,
salary = 0
},
[302] = {
name = "John",
age = "12",
address = {""},
job = "Marketing",
job a = "some job",
job b = {"some job"},
car = 0,
salary = 0
},
答え2
以下のコマンドでテストし、正常に動作しました
指示
for i in `cat filea`; do sed -n '/'$i'/,/^[[:space:]]\{4\}\},$/p' fileb; done
出力
[300] = {
name = "John",
age = "12",
address = {""},
job = "Marketing",
job a = "some job",
job b = {"some job"},
car = 0,
salary = 0
},
[302] = {
name = "John",
age = "12",
address = {""},
job = "Marketing",
job a = "some job",
job b = {"some job"},
car = 0,
salary = 0
},
[303] = {
name = "John",
age = "12",
address = {
"Person street address"
},
job = "Marketing",
job a = "some job",
job b = {
"His job description"
},
car = 0,
salary = 0
},
答え3
sed
次の行を使用すると役立つかもしれません。
while read n; do sed -n -e "/^\[$n\]/,/^},$/p" b.txt; done < a.txt