2

This is similar to question VIM: insert or delete data based on position

I am trying to replace (not just insert) the desired text at position 7 in every line in a file. Based on the regex provided in the solution in the above question, I tried:

a. %s/\%=7c/text/  (failed error message - illegal character)
b. %s/\%7c/text/g   (says correct amount of lines / changes were made BUT blank space is still there after "text")
c. %s/\%7c/text/ (same as b)
Community
  • 1
  • 1
lostinthebits
  • 661
  • 2
  • 11
  • 24

3 Answers3

3

The /%7c will insert at character 7

you'll want your match to be the following, so that it includes the next character:

%s/\%7c./text/
Bob Vale
  • 18,094
  • 1
  • 42
  • 49
2

To add to Bob Vale's correct answer, the \%c atom is a zero-width match. That is, it only limits the match (here: to the character position), but it does not consume any characters. You need to do that by putting a corresponding atom behind it (here: . will match any character). The better-known \< atom behaves the same.

Note for non-ASCII encodings

There's a caveat: the \%c matches byte numbers of the underlying representation, so it won't work as expected when there are non-ASCII characters. It's likely that you're actually interested in the screen column (this also matters when there's a <Tab> character in front of the match: it counts as one byte, but has a screen column width of between 1 and 8). Vim calls this virtual column and has the \%v atom for it.

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
0

I find it easier to use visual block mode for that kind of things (there is little chance I'll remember that zero-width expression syntax).

javs
  • 798
  • 10
  • 28