Search code examples
vi

How to align a column using the vi editor?


I have a column in numbers like below

-0.01343
0.002
-1.1234

I want to align the column in vi editor like below

-0.01343
 0.002
-1.1234

Solution

  • So, you want to insert a space before each line not starting with a minus:

    The appropriate command is is :%s/^\([^-]\)/ \1/

    This breaks down as:

    : - start command

    %s - regex on all lines

    /^\([^-]\) - matching the start of the line, followed by any character other than -, which we will call group 1

    / \1 - replace with a space followed by whatever was in group 1

    / - end regex, perform no more than once on each line

    Other options:

    If you select the intended lines in a visual block, typing : will start the command with '<,'>. Then move onto the regex starting with s (no %) and it will apply only to the selected lines.

    If you end it with a /c it will ask for confirmation on each replacement. If you end it with /g it will work multiple times per line if applicable. /gc is valid.

    If you'd wanted the decimal points to be aligned, rather than the first digits, that's more complex and probably cannot be done with a simple command in vi or vim.