我有兩個文件,我想做的是使用歸檔一個並搜尋號碼文件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 機器上的任何 shell 中使用任何 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