4

I'm formatting a multiple-choice quiz to be imported into an LMS. The questions are currently formatted like this, with the asterisk indicating the correct solution:

1. Question text
a. First answer
*b. Second answer
c. Third answer
d. Fourth answer

And I need to change the format to:

1. Question text
a. First answer
b. Second answer
c. Third answer
d. Fourth answer
Answer: b

One option is :g/^\*b\./norm x}OAnswer: b, but then I need run similar commands for a, c, and d to make sure I captured all the answers. It would be great if I could use backreferences, like :g/^\*\([a-d]\)\./norm x}OAnswer: \1 but I know backreferences won't work. I thought of yanking the correct answer's letter, }-ing down, and pasting it, but I'm drawing a blank as to how to write the commands to accomplish that. Any ideas?

Blair
  • 43
  • 2

3 Answers3

3

It would be great if I could use backreferences, like :g/^\*\([a-d]\)\./norm x}OAnswer: \1 but I know backreferences won't work. I thought of yanking the correct answer's letter, }-ing down, and pasting it, but I'm drawing a blank as to how to write the commands to accomplish that. Any ideas?

:g/^\*[a-d]\./norm! xyl}OAnswer: ^[p

Where ^[ is typed as <c-v><esc> (or <c-q><esc> depending on your config).

Matt
  • 20,685
  • 1
  • 11
  • 24
  • It seems to assumes that there is a blank line after the paragraph. – Vivian De Smedt Sep 12 '23 at 06:25
  • 1
    @VivianDeSmedt Yes, just like in the OP. Might be wrong for the last para, of course, but, imo, that's a very minor problem. – Matt Sep 12 '23 at 07:17
  • This is great -- I thought another solution might be something like this, but forgot about switching from insert to normal mode in a :g command. Sorry to be dense, but what does the grouping do here? I see the ( and ) but no \1 – Blair Sep 12 '23 at 14:18
  • @Blair Well, actually nothing. That was due to copy-paste. – Matt Sep 12 '23 at 17:24
2

This one assumes that the "blocks" are all followed by at least one empty line:

:g/^\*/s/^\*//|t/^$/-|s/^\(.\).*/Answer: \1
  • The :help :g command matches lines that start with *.
  • The first :help :s command removes the leading *.
  • The :help :t command copies the current line to after the last choice line.
  • The second :s command prepends Answer: to the letter and gets rid of what comes after it.

Using only Ex commands for fun and profit.

romainl
  • 40,486
  • 5
  • 85
  • 117
1

I would do:

:%s/\v^\*(.)(%(.+\n)+)/\1\2Answer: \1/

Where:

  • \v turn super magic on (to avoid to have to escape the special signs)
  • ^\* match the start of the line that starts with * (the super magic force you to escape the special sign when they are meant to match literally)
  • %(.+\n) match a line (but not create a group that can be referenced)
  • (%(.%\n)+) match the rest of the paragraph (excluding blank line)
Vivian De Smedt
  • 16,336
  • 3
  • 18
  • 37