0

I have seen many posts like this, that tell how to replace text column wise in vim.

That is straightforward when columns are arranged with fixed widths.

How about using vim to replace text in a given column when the columns are not aligned.

E.g.

I have a file with multiple columns:

col1 -col2 0.col3 +col4  col5.
col1  0.col2 +col3  col4.0  -col5
col1.0 0.col2 +col3  -col4 col5
col1 col2.0  +col3 0.col4  -col5
-col1 col2.0  +col3 0.col4  col5
col1 -col2  +col3 0.col4  col5.0

and I want it to look like

col1       0.col3 +col4  col5.
col1         +col3  col4.0  -col5
col1.0        +col3  -col4 col5
col1         +col3 0.col4  -col5
-col1         +col3 0.col4  col5
col1        +col3 0.col4  col5.0
Community
  • 1
  • 1
kvaibhav
  • 163
  • 1
  • 1
  • 7

2 Answers2

3
  • Here is a convoluted solution using a substitution:

    :%s/^\S*\s*\zs\(\S*\)/\=repeat(" ", len(submatch(1)))/g
    

    See :help :s, :help submatch(), :help repeat().

  • And here is a much simpler one using a macro:

    :%normal WvEr <-- there's a space after the 'r'
    

    See :help :normal.

romainl
  • 186,200
  • 21
  • 280
  • 313
0

You can use this:

:%s/^\(.\{-}. \)\{1}\zs\(.\{-}. \)/ /g

You can change \{1} to desired column number, note that is 1 less than actual column number. Also you can modify this regex a little more to erase multiple consecutive columns. And so on and so forth.

for transform this:

col1 -col2 0.col3 +col4  col5.
col1  0.col2 +col3  col4.0  -col5
col1.0 0.col2 +col3  -col4 col5 
col1 col2.0  +col3 0.col4  -col5
-col1 col2.0  +col3 0.col4  col5 
col1 -col2  +col3 0.col4  col5.0

to this:

col1       0.col3 +col4  col5.
col1       +col3  col4.0  -col5
col1.0       +col3  -col4 col5
col1        +col3 0.col4  -col5
-col1        +col3 0.col4  col5
col1        +col3 0.col4  col5.0
Alan Gómez
  • 211
  • 1
  • 6