0

I'm working on a subtitle document (.srt) which has thousand of lines. But this issue is not about the subtitle documents, I going to export as plain text to read after. To see the dialogs line by line as a normal sentence, I deleted the dialog number and timestamp lines via record a macro.

But some dialog lines seems to apart from each other. I need to join all the separated dialogs as line by line until the last dot, question or exclamation mark of them.

Example 1

See the church spire
over the trees?

Or end of the line could include comma:

Example 2

See the church spire,
over the trees?

I would like to merge these example lines like that:

Expected result

See the church spire over the trees?

How can I create a macro for that?

1 Answer 1

2

Personally I wouldn't use a macro but :substitute; this seems to do what you want:

:%s/\([^.?!]\)\n/\=(submatch(1) == ',' ? '' : submatch(1)) .. ' '/

In the find pattern:

\([^.?!]\)\n

The \n is a literal newline, and [^…] matches any character not in this group. In this case, anything that is NOT a ., ?, or !. For "See the church spire" it matches the "e". We capture this in a group with \(…\) so we can add the "e" back later.

So this matches any newline not precedeed by a ., ?, or !.


In the replace pattern:

\=(submatch(1) == ',' ? '' : submatch(1)) .. ' '

We use \= to start an expression replacement; you can use any VimScript expression here. We check if the group we captured is a ,, if so we don't add it back because we want to remove that. We add any other character back, as that's the last letter. We always add a space.

It's a bit easier to read with some newlines added:

(
   submatch(1) == ',' ?
       '' :
       submatch(1)
) .. ' '

So a document like this:

See the church spire
over the trees?
See the church spire,
over the trees?
See the church spire
asdf
over the trees?
See the church spire,
over the trees?
a sentence.
another sentence!
woot?

Becomes:

See the church spire over the trees?
See the church spire over the trees?
See the church spire asdf over the trees?
See the church spire over the trees?
a sentence.
another sentence!
woot?
2
  • Thanks for the detailed explanation and solution. I did copy and paste it what you suggests and the patters are worked perfectly! 🙏Now, I being try to understand how this actually working, cause it's a bit complicated for me. 🙂
    – Pascowl
    Jul 5 at 18:14
  • It can certainly be a much to take in @Pascowl. I didn't "just write" it in one go, I first made a simpler version which just joines lines, and then I expanded on that to remove the comma (which took me a few tries). It's much easier to really understand these things if you write themselves from the start, rather than merely looking at the end-result. Jul 7 at 0:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.