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}
1

1 Answer 1

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.

2
  • E117: Unknown function: execute
    – juaninf
    Commented Jun 9, 2018 at 20:22
  • you should update your vim then
    – Mass
    Commented Jun 9, 2018 at 20:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.