我搜索了很多答案,但什么也找不到。
我有一个文本文件(来自一次考试),答案在另一个文件中。我设法在每个问题的末尾添加了文本" answer:“,但现在我找不到一种方法将答案从file2提取到file1中。
file1:
问题: 179 - Alterando-se ongulo de ataque de 0º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-se ongulo de ataque de 0ºpara 6º,一个抵抗者寄生:
a Aumenta
b) Não se altera
c) Diminui
d) Impossível de se determinar
Answer: B发布于 2014-03-11 01:05:15
对于这一点,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但是,如果问题头或答案文件中的数据格式不是完全规则,这就不是完全健壮的。
https://stackoverflow.com/questions/22304812
复制相似问题