我搜索了很多答案,但却找不到任何答案。
我有一个文本文件(来自考试),答案在另一个文件中。 我设法在每个问题的末尾添加了文本“答案:”,但现在我找不到从file2获取答案到文件1的方法。
文件1:
问题:179 - Alterando-seoââululodeataquede0ºparaº6,一个抵抗寄生虫:
a Aumenta
b) Não se altera
c) Diminui
d) Impossível de se determinar
Answer:
file2的:
177)C
178)A
179)B
180)B
我尝试使用sed但到目前为止没有成功,任何建议都会受到赞赏。
每个问题都会重复file1结构,但有时问题可以有多行。
所需的输出应为:
问题:179 - Alterando-seoââululodeataquede0ºparaº6,一个抵抗寄生虫:
a Aumenta
b) Não se altera
c) Diminui
d) Impossível de se determinar
Answer: B
答案 0 :(得分:2)
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
如果问题标题的格式或答案文件中的数据不完全正常,这并不完全可靠。