Reputation: 107
I have 3 files. One is a list of foods and categories:
food="rice"
product="cereal"
food="beans"
product="bean"
food="cake"
product="bakery"
food="lettuce"
product="leaves"
The second is a list of only of the foods:
food="rice"
food="beans"
food="cake"
food="lettuce"
On the third file I have lines that contain strings of /food file (e.g. /food="rice") and I need to replace these strings by the corresponding product listed on the first file. To simplify: find the string from file 2 on file 3 and replace by the next line of file one on file 3. I thought maybe a combination of grep and sed but I can't figure out how to... The third file looks something like this
>[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?
And I need it to look like...
>[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?
Upvotes: 0
Views: 86
Reputation: 3363
Here is a solution using sed
:
sed -f <(sed 'N;s/\n/\//;s/^/s\//;s/$/\//' one) three
If every line of the first file really starts with whitespace, that becomes
sed -f <(sed 'N;s/ *//g;s/\n/\//;s/^/s\//;s/$/\//' one ) three
Upvotes: 1
Reputation: 203655
I can't see what file2 would be used for.
$ 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?
Upvotes: 0
Reputation: 67507
here is a sed/awk
combination
$ 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?
Upvotes: 0