我有3个文件。一个是食物和类别的列表:
food="rice"
product="cereal"
food="beans"
product="bean"
food="cake"
product="bakery"
food="lettuce"
product="leaves"
第二个是只列出食物的列表:
food="rice"
food="beans"
food="cake"
food="lettuce"
在第三个文件中,我有包含大米文件字符串的行(例如,/food=“/food”),我需要将这些字符串替换为第一个文件中列出的相应产品。为了简化:在文件3中找到文件2中的字符串,并替换为文件3中文件1的下一行。我想可能是grep和sed的组合,但我不知道如何...第三个文件如下所示
>[food="rice"] [some other sutff] [calories=398]
Here is a recipe with rice
>[food="beans"] [some other sutff] [calories=250]
Here is a recipe with beans
>[food="cake"] [some other sutff] [calories=100]
Here is a recipe for cake
>[food="lettuce"] [some other sutff] [calories=02]
Why would you need a recipe for lettuce?
我需要它看起来像..。
>[product="cereal"] [some other sutff] [calories=398]
Here is a recipe with rice
>[product="bean"] [some other sutff] [calories=250]
Here is a recipe with beans
>[product="bakery" [some other sutff] [calories=100]
Here is a recipe for cake
>[product="leaves"] [some other sutff] [calories=02]
Why would you need a recipe for lettuce?
发布于 2018-08-22 15:11:37
这是一个使用sed
的解决方案
sed -f <(sed 'N;s/\n/\//;s/^/s\//;s/$/\//' one) three
如果第一个文件的每一行都以空格开头,那么就变成了
sed -f <(sed 'N;s/ *//g;s/\n/\//;s/^/s\//;s/$/\//' one ) three
发布于 2018-08-22 03:36:06
下面是一个sed/awk
组合
$ sed -f <(awk ' {gsub(/ /,"")}
NR==FNR {if(/food/) k=$0; if(/product/) a[k]=$0; next}
$0 in a {print "s/" $0 "/" a[$0] "/g"}' f1 f2) f3
>[product="cereal"] [some other sutff] [calories=398]
Here is a recipe with rice
>[product="bean"] [some other sutff] [calories=250]
Here is a recipe with beans
>[product="bakery"] [some other sutff] [calories=100]
Here is a recipe for cake
>[product="leaves"] [some other sutff] [calories=02]
Why would you need a recipe for lettuce?
发布于 2018-08-22 19:53:09
我不明白file2会被用来做什么。
$ cat tst.awk
BEGIN { FS="[][]" }
NR==FNR {
gsub(/^[[:space:]]+|[[:space:]]+$/,"")
if (NR%2) { food = $0 }
else { map[food] = $0 }
next
}
{
sub(/\[[^][]+/,"["map[$2])
print
}
$ awk -f tst.awk file1 file3
>[product="cereal"] [some other sutff] [calories=398]
Here is a recipe with rice
>[product="bean"] [some other sutff] [calories=250]
Here is a recipe with beans
>[product="bakery"] [some other sutff] [calories=100]
Here is a recipe for cake
>[product="leaves"] [some other sutff] [calories=02]
Why would you need a recipe for lettuce?
https://stackoverflow.com/questions/51954936
复制相似问题