Search code examples
vim

Delete a specific Column in VIM/gvim with out using Visual Block mode


Sample Input File

+--------------------+---------+---------
|           Name     |   S1    |    S2
+--------------------+---------+---------
|           A        | -4.703  | -2.378  
|           B        | -3283.2 | -3204.5 
|           C        |  8779   |  7302   
|           D        |  22078  |  18018  
+--------------------+---------+---------

It is required to remove the S1 Column, i.e

Desired Output

+--------------------+---------
|           Name     |   S2    
+--------------------+---------
|           A        | -2.378    
|           B        | -3205.5  
|           C        |  7302      
|           D        |  18018    
+--------------------+---------

Can anyone help with this

thanks


Solution

  • In command mode:

    :%s/^\([[+|][^+|]\+\)[+|][^+|]\+/\1/
    

    This uses vim's built-in sed-like search and replace command. Here's the breakdown:

    % - for the entire file

    s - search for

    /^ - the start of line

    \([[+|][^+|]\+\) - followed by + or |, followed by any number (\+) of anything that is not + or |. This will get the first column, which we want to keep, so put it in a capture group by surrounding it with \( and \)

    [+|][^+|]\+ - followed by + or |, followed by any number (\+) of anything that is not + or |. This will get the second column, which we don't want to keep, so no capture group.

    /\1/ - replace everything we matched with the first capture group (which contains the first column). This effectively replaces the first and second column with the contents of the first column.

    Like I said, vim's regex are pretty much identical to sed, so you if you look through this tutorial on sed you'll probably pick up a lot of useful stuff for vim as well.

    Edit

    In response to the OP's request to make this more generally capable of deleting any column:

    :%s/^\(\([[+|][^+|]\+\)\{1\}\)[+|][^+|]\+/\1/
    

    The index inside of the \{\}, now deletes the column indicated. Think of it like an array index (i.e. starts at zero). So \{0\} now deletes the first column, \{1\} deletes the second, and so on.