Sed 在另一个文件上查找匹配项时从一个文件添加文本

Sed 在另一个文件上查找匹配项时从一个文件添加文本,sed,pattern-matching,Sed,Pattern Matching,我搜索了很多答案,但没有找到任何答案 我有一个文本文件(来自考试),答案在另一个文件中。 我设法在每个问题的末尾添加了“答案:”文本,但现在我找不到从文件2到文件1中提取答案的方法 文件1: 问题:179–0°第6°段的奥恩古洛交替,一个抵抗者: a Aumenta b) Não se altera c) Diminui d) Impossível de se determinar Answer: a Aumenta b) Não se altera c) Diminui d)

我搜索了很多答案,但没有找到任何答案

我有一个文本文件(来自考试),答案在另一个文件中。 我设法在每个问题的末尾添加了“答案:”文本,但现在我找不到从文件2到文件1中提取答案的方法

文件1:


问题:179–0°第6°段的奥恩古洛交替,一个抵抗者:

a Aumenta 
b) Não se altera 
c) Diminui 
d) Impossível de se determinar 
Answer:
a Aumenta 
b) Não se altera 
c) Diminui 
d) Impossível de se determinar 
Answer: B
文件2:

177)C
178)A
179)B
180)B
我尝试使用sed,但迄今为止没有成功,任何建议都将不胜感激

file1结构对每个问题都重复,但有时问题可以有多行

所需输出应为:


问题:179–0°第6°段的奥恩古洛交替,一个抵抗者:

a Aumenta 
b) Não se altera 
c) Diminui 
d) Impossível de se determinar 
Answer:
a Aumenta 
b) Não se altera 
c) Diminui 
d) Impossível de se determinar 
Answer: B

sed
很难成为我选择的工具,而在Awk中它相当容易

awk 'NR==FNR {
        # NR is equal to FNR when we are reading the first input file
        # Store the right answer for each question in an array
        split($1, b, /\)/)
        # If the input was 123)A, the array b now contains "123" and "A"
        a[b[1]] = b[2]
        # We are done; skip to next line
        next
    }
    # If we are here, we are in the second file.  Find a question delimiter
    /Question: [0-9]+/ {
        # If we have the previous question in memory, print its answer first
        if (q>0) { print "\nAnswer: " a[q] "\n\n" }
        # Remember index for this question
        q=$2
    }
    # If we are this far, perform the default action, that is, print this line
    # "1" is a shorthand for "print the current line"
    1
    # At the end of the file, print the last remaining answer
    END { print "\nAnswer: " a[q] "\n\n" }' file2 file1

但是,如果问题标题或答案文件中的数据格式不完全规则,则这并不完全可靠。

始终有4个答案,文件1的结构相同,即问题1的1行空行4行回复,比下一个问题的1行空行?同时给出一个期望的输出,这有助于格式化和理解我编辑原始文本以包含您需要的答案。谢谢你对我的问题感兴趣。谢谢你的快速回答,但我没能成功。我将您的解决方案放在一个bash脚本文件中,并尝试运行它,后跟文件名,但它只是锁定了控制台。我必须按Ctrl+C组合键才能取回它。(我在这样做之前允许了超过15分钟的时间…)感谢您的反馈,并对草率的复制/粘贴表示抱歉。我修复了几个问题,并确认它现在对我有效。抱歉之前的回答不完整。这次脚本确实有效,但对于一些问题,输出结果并不像预期的那样。我将添加一个outputWell示例,答案中有几个警告。如果你能用角落案例更新你的问题,那么提供一个适合你的答案就更容易了。问题:179–Alterando se o–ngulo de ataque de 0º第6º段,答案:答案:b问题:180–考虑到总重量为100平方米的比索10000公斤的空中导航,答:问题:0,01平方米/千克回答:问题:100平方米回答:c)问题:1000平方米回答:d)问题:0,01平方米回答:答案: