Yewge
Yewge

Reputation: 1974

Vim: padding out lines with a character

How can I repeatedly add a character at the end of one or more lines, padding out the line(s) to a specific column?

For instance:
('x' represents column 40, not a character on the line; and there are no spaces or tabs after the text)

line one                               x
line two                               x
line three                             x
line eleventy-billion                  x

becomes

line one ------------------------------x
line two ------------------------------x
line three ----------------------------x
line eleventy-billion -----------------x

Upvotes: 17

Views: 5199

Answers (2)

Eevee
Eevee

Reputation: 48546

A combination of \=, submatch(), and repeat():

:%s/\v^.*$/\= submatch(0) . " " . repeat("-", 39 - len(submatch(0)))

Upvotes: 30

Jason Cemra
Jason Cemra

Reputation: 573

Just in case anyone stumbles across this in the future, I have an alternative way that I use which (I think) is easier to remember on the rare occasion that one would need to manually pad out some lines.

Input Text:

Here are some words
They do not have equal length
I want to insert characters after them until column 40
How to do?

What you type:

gg                // Position cursor anywhere on first line you want to pad
q1$40A-<Esc>d40|q // Looks more complex than it is.
                  // Here, in English:
                  // 1. Record a macro in slot 1
                  // 2. Go to the end of the line, then *A*ppend a '-' 40 times
                  // 3. Delete from cursor position (which is still at the end of the line) to column 40
                  // 4. Stop recording
:1,4normal @1     // Repeat macro "1" for every line

Output Text:

Here are some words-----------------
They do not have equal length-------
I want to insert characters after t-
How to do?--------------------------

Hopefully you can figure out how to adjust the various parts of the command to make it do exactly what you want. Note that text which is longer than your desired column span will be truncated (demonstrated on line 3).

Upvotes: 11

Related Questions