How to remove text from all lines between two columns?

vim
11,613

Solution 1

Position your cursor in d, then press Ctrl-V, l, G and d.

  • Ctrl-v enters visual block mode;
  • l expands the visual selection one character to the right;
  • G expands the selection to the last line;
  • d deletes the selection.

Solution 2

Your question is very similar to this one.

To delete the columns 3 through 5 for all lines in the file:

:%normal 3|d6|

In order to delete an specific line interval (80 to 90), use this:

:80,90normal 3|d6|

If you're not familiar with the normal command nor with the | "motion" there goes a quick explanation:

  1. The normal command execute the following commands in the normal mode;
  2. The | "motion" moves the cursor to a specified column, so 3| moves the cursor to the 3rd column;
  3. Then i deletes everything (d) until the 5th column (6|).

Solution 3

For spontaneous editing, I would use blockwise visual mode via CTRL-V (often mapped to CTRL-Q on Windows), then d to delete it.

If you do this often, for a large range / the entire buffer, or repeatedly, I would use a substitution that starts matching in a virtual column, and extends (up) to the end column, like for your example:

%s/\%3v.*\%<7v//

Solution 4

You can use search and replace:

:%s/..\zs...\ze

or in a more general form:

:%s/.\{2}\zs.\{3}\ze

where the first number (2) is the index of the column (zero based) and the second number (3) is the count of characters the column has.

Explanation:

:%s/ search and replace in the whole buffer.

.\{2}\zs find two characters and set the beginning of match here.

.\{3}\ze find three characters and set the end of match here.

Omit the replacement string since you want to delete the match.

HTH

Share:
11,613
read Read
Author by

read Read

Updated on July 22, 2022

Comments

  • read Read
    read Read about 2 months

    I would like to remove the content for all lines between two columns. How do I do this?

    For example, I want this:

    abcdefg
    hijklmn
    opqrstu
    

    To become this if I remove text between columns 3 through 5:

    abfg
    himn
    optu
    
  • Lumi
    Lumi over 10 years
    It's better to do first G and then l because you may have to redo l if G lands you on an empty line.
  • Ingo Karkat
    Ingo Karkat over 10 years
    Your solution is character-based, not column-based. This differs for double-width (e.g. Chinese) characters, <Tab>, and non-printable characters like ^P (CTRL-P).
  • Tassos
    Tassos over 10 years
    @IngoKarkat You're right. I din't read the whole of your answer (I stopped after I read CTRL-V). +1 for your answer.
  • timbo
    timbo almost 7 years
    Nice but unfortunately with vim 7.4.903+, the G expands the selection to the bottom of file and to the left of file. So in the original example, all characters would be removed to the left. Instead, you will need to use the l key to ensure that the highlighted area is the area you want to remove.