我有两个文件,我想要做的是使用归档一个并搜索号码文件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