首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在一个文件中找到匹配项时添加另一个文件中的文本

在一个文件中找到匹配项时添加另一个文件中的文本
EN

Stack Overflow用户
提问于 2014-03-10 23:47:01
回答 1查看 43关注 0票数 0

我搜索了很多答案,但什么也找不到。

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

file1:

问题: 179 - Alterando-se o­ngulo de ataque de 0ºpara 6º,一个抵抗者寄生:

代码语言:javascript
复制
a Aumenta 
b) Não se altera 
c) Diminui 
d) Impossível de se determinar 
Answer:

file2:

代码语言:javascript
复制
177)C
178)A
179)B
180)B

我尝试使用sed,但到目前为止没有成功,任何建议都将不胜感激。

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

所需的输出应为:

问题: 179 - Alterando-se o­ngulo de ataque de 0ºpara 6º,一个抵抗者寄生:

代码语言:javascript
复制
a Aumenta 
b) Não se altera 
c) Diminui 
d) Impossível de se determinar 
Answer: B
EN

回答 1

Stack Overflow用户

发布于 2014-03-11 01:05:15

对于这一点,sed几乎不是我的首选工具,而在Awk中它相当容易。

代码语言:javascript
复制
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

但是,如果问题头或答案文件中的数据格式不是完全规则,这就不是完全健壮的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22304812

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档