У меня есть два файла, я хочу использовать ихфайл аи номер поиска вфайл би вывести все его скобки, включая искомую строку. Я не уверен, что это так называется.
Файл а:
300
302
303
Файл б:
[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
Если у вас нет доступа к парсеру для этого конкретного формата и ваши записи действительно такие простые и регулярные, как вы показываете, то это будет работать с использованием любого awk в любой оболочке на любой машине UNIX:
$ 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