2

I am trying to search and replace certain pattern "\x" to REPLACE_counter. Where counter goes from $0$ to $N$. The text is

\x    & \x       & \x    & \x    & \x \\ \cline{1-1}
\x    & \x       & \x    & \x    & \x \\ \cline{1-1}

I found the next command

let i=1 | g/\\x/.,.s//\='REPLACE_'.i/ | let i=i+1

but it only works for the first match in each line, i.e. I get

REPLACE_1   & \x       & \x    & \x    & \x \\ \cline{1-1}
REPLACE_2    & \x       & \x    & \x    & \x \\ \cline{1-1}

How can I modify that command to get

REPLACE_1   & REPLACE_2 & REPLACE_3& REPLACE_4& \xREPLACE_5 \\ \cline{1-1}
REPLACE_6    & REPLACE_7      & REPLACE_8    & REPLACE_9    & REPLACE_10 \\ \cline{1-1}
juaninf
  • 153
  • 4
  • https://vi.stackexchange.com/questions/4750/insert-subsequent-numbers-in-a-substitution-pattern/4751#4751 – Mass Jun 09 '18 at 20:59

1 Answers1

2

In vim 7.4.2008 and later, you can do this with substitute and execute():

:let i = 1
:%s/\\x/\='REPLACE_'.i.execute('let i+=1')/g

\= allows you to use an expression as the replacement string. execute() invokes an ex command (let) in an expression. In this case execute() returns empty string. We use /g to replace multiple instances per line.

Mass
  • 14,080
  • 1
  • 22
  • 47