首页 > 解决方案 > 用另一个列表中的下一行替换列表中的字符串

问题描述

我有 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="rice"),我需要将这些字符串替换为第一个文件中列出的相应产品。为了简化:在文件 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?

标签: linuxawksedgrep

解决方案


这是使用的解决方案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

推荐阅读